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 回答