0

正規表現を使用していくつかの単語を検索し、単語/文字列で何かを行います。

私の例:

見つけたすべての単語でタグを設定したくあり<strong>ません:

$string = 'Hello, there is foo, after there is bar but now I need foo bar.'

$html = preg_replace('/(foo|bar)/', '<strong>$1</strong>', $string);

$html will be 'Hello, there is <strong>foo</strong>, after there is <strong>bar</strong> but now I need <strong>foo</strong> <strong>bar</strong>.'

そして、それらが検索された他の1つの単語に続く1つの単語である場合、その結果:

'Hello, there is <strong>foo</strong>, after there is <strong>bar</strong> but now I need <strong>foo bar</strong>.'

正規表現を変更して、私たちの間の2つの単語を取得し、タグを区切らずに作業するにはどうすればよいですか?

ありがとう

4

3 に答える 3

2
$search = 'foo bar blah';
$string = 'Hello, there is foo, after there is bar but now I need foo bar blah.';

$search = preg_quote($search);
$regex = $search . '|' . str_replace(' ', '|', $search);

$html = preg_replace('/\b(' . $regex . ')\b/', '<strong>$1</strong>', $string);

echo $html; // Outputs: Hello, there is <strong>foo</strong>, after there is <strong>bar</strong> but now I need <strong>foo bar blah</strong>.
于 2013-01-13T16:07:07.117 に答える
1
于 2013-01-13T16:14:35.723 に答える
0
$string = 'Hello, there is foo, after there is bar but now I need foo bar.';
$string.= ' Lets throw a bar foo in there as well!';

$html = preg_replace('/(bar foo|foo bar|foo|bar)/', '<strong>$1</strong>', $string);

echo $html;
于 2013-01-13T16:07:07.753 に答える