2017-01-30 2 views
1

単語と文字列の配列を持ち、文字列内の単語にハッシュタグを追加して、配列内で一致する文字を追加します。私は単語を見つけると交換し、このループを使用します。preg replaceは、単語を検出するときに文字以外の文字を無視します。

foreach($testArray as $tag){ 
    $str = preg_replace("~\b".$tag."~i","#\$0",$str); 
} 

問題:「ある」と私の配列に「隔離」私は言葉を持って言うことができます。私は出力に#isolateを得ます。これは、単語 "分離"が "is"のために1回、 "分離"のために1回見つけられることを意味する。パターンは "#isoldated"が "is"で始まっていないことを無視し、 "#"で始まります。

私は例をもたらすが、これだけexampl電子であり、私はこの1つだけを解決する必要はありませんが、他のすべてのpossiblity:

$str = "this is isolated is an example of this and that"; 
$testArray = array('is','isolated','somethingElse'); 

出力は次のようになります。

this #is ##isolated #is an example of this and that 

答えて

1

両端に単語境界で囲まれた交替グループを持つ正規表現を作成し、すべてのマッチを1回のパスで置き換えることができます:

$str = "this is isolated is an example of this and that"; 
$testArray = array('is','isolated','somethingElse'); 
echo preg_replace('~\b(?:' . implode('|', $testArray) . ')\b~i', '#$0', $str); 
// => this #is #isolated #is an example of this and that 

PHP demoを参照してください。

正規表現は

~\b(?:is|isolated|somethingElse)\b~ 

のようになります。そのonline demoを参照してください。

アプローチを有効にしたい場合は、\b"~\b(?<!#)".$tag."~i","#\$0"の後ろに負のルックアヘッドを追加することができます。 lookbehindは、#の前にあるすべての一致に失敗します。 this PHP demoを参照してください。

$str = "this is isolated is an example of this and that"; 
$testArray = array('is','isolated','somethingElse'); 

$hash = array_flip(array_map('strtolower', $testArray)); 

$parts = preg_split('~\b~', $str); 

for ($i=1; $i<count($parts); $i+=2) { 
    $low = strtolower($parts[$i]); 
    if (isset($hash[$low])) $parts[$i-1] .= '#'; 
} 

$result = implode('', $parts); 

echo $result; 

この方法では、あなたの文字列は次のとおりです。

1

それを行うための方法は、(in_arrayの使用を避けるために)言葉によって、あなたの文字列を分割し、単語のあなたの元の配列と連想配列を構築することです配列内の単語の数に関係なく、1回だけ処理されます。

関連する問題