2

これは私が取得しようとしているものです。 My longest text to testたとえば、検索すると取得Myする必要がありますMy longest

この関数を使用して、最初に入力の完全な長さを取得してから、「 」を検索して切り取ってみました。

$length = strripos($text, $input) + strlen($input)+2;

$stringpos = strripos($text, ' ', $length);

$newstring = substr($text, 0, strpos($text, ' ', $length));

しかし、これは最初にしか機能せず、現在の入力の後にカットされます。つまり、 My lonisMy longestと notMy longest textです。

常に次の単語を取得して、正しい結果を得るためにこれをどのように変更する必要がありますか。休憩が必要かもしれませんが、正しい解決策が見つかりません。

アップデート

より良い解決策が見つかるまで、これが私の回避策です。私が言ったように、部分語は機能するはずなので、配列関数の操作は機能しません。そこで、以前のアイデアを少し拡張しました。基本的な考え方は、初回と次回で異なることです。コードを少し改善しました。

function  get_title($input, $text) {
    $length       = strripos($text, $input) + strlen($input);   
$stringpos = stripos($text, ' ', $length);
// Find next ' '
$stringpos2 = stripos($text, ' ', $stringpos+1);

if (!$stringpos) {
    $newstring = $text;
} else if ($stringpos2) {
    $newstring = substr($text, 0, $stringpos2);
}  }    

きれいではありませんが、ちょっとうまくいくようです^^。とにかく、あなたの誰かがより良い解決策を持っているかもしれません。

4

3 に答える 3

4

使用してみることができますexplode

$string = explode(" ", "My longest text to test");
$key = array_search("My", $string);
echo $string[$key] , " " , $string[$key + 1] ;

大文字と小文字を区別しないで次のレベルに進むことができますpreg_match_all

$string = "My longest text to test in my school that is very close to mY village" ;
var_dump(__search("My",$string));

出力

array
  0 => string 'My longest' (length=10)
  1 => string 'my school' (length=9)
  2 => string 'mY village' (length=10)

使用する機能

 function __search($search,$string)
 {
    $result = array();
    preg_match_all('/' . preg_quote($search) . '\s+\w+/i', $string, $result);
    return $result[0]; 
 }
于 2012-09-30T23:45:42.647 に答える
2

簡単な方法は、空白で分割し、現在の配列インデックスと次のインデックスを取得することです。

// Word to search for:
$findme = "text";

// Using preg_split() to split on any amount of whitespace
// lowercasing the words, to make the search case-insensitive
$words = preg_split('/\s+/', "My longest text to test");

// Find the word in the array with array_search()
// calling strtolower() with array_map() to search case-insensitively
$idx = array_search(strtolower($findme), array_map('strtolower', $words));

if ($idx !== FALSE) {
  // If found, print the word and the following word from the array
  // as long as the following one exists.
  echo $words[$idx];
  if (isset($words[$idx + 1])) {
    echo " " . $words[$idx + 1];
  }
}

// Prints:
// "text to"
于 2012-09-30T23:45:05.717 に答える
2

それを行う簡単な方法があります。文字列関数は、特定のものを探したくないが、定義済みの長さのものを切り取る場合に便利です。それ以外の場合は、正規表現を使用します:

 preg_match('/My\s+\w+/', $string, $result);

 print $result[0];

ここで、Myは文字通りの最初の単語を探します。そして\s+、いくつかのスペースのために。while\w+は単語の文字に一致します。

これにより、学習する新しい構文がいくつか追加されます。ただし、回避策と同じことを達成するためのより長い文字列関数コードよりも脆弱ではありません。

于 2012-09-30T23:45:16.383 に答える