【发布时间】:2015-11-21 10:33:24
【问题描述】:
我正在尝试在特定字符串周围加粗两个单词,例如问题How can I bold two words around a string within a string, but not overlap sentences?
解决方案为
$string = preg_replace("/\\b(\\w+ +){0,2}$query( +\\w+){0,2}\\b/i",
'<strong>$0</strong>',
$string);
这对我来说很好,但是,我想将其他字符串(非粗体)替换为“...”,例如考虑字符串
$string = 'Then split that sentence into words and add some tags in two words before and after the matching word.
Since you only have one sentence to work on, you\'d include a check to make sure you didn\'t go out of bounds of the word array.
Sometimes you need to disable/enable the form element like input or textarea. Jquery helps you to easily make this with setting disabled attribute';
如果我正在搜索“the”这个词,这可以看起来像
... 在匹配词之后 ... 单词数组的边界 ...禁用/启用表单元素...
此解决方案的另一个缺点是它只搜索两个空格之间的字符串。可以修改它以搜索任何字符串吗?
最后,我们是否可以对可以找到的搜索数量设置一个限制,以便在再次搜索之前文本中的字符串“the”时,我将限制设置为我应该只得到一个
... 在匹配词之后 ...
【问题讨论】:
-
使用
preg_match将搜索限制为1。 -
@stribizhev,你的两个建议都给
Warning: preg_replace() expects at least 3 parameters, 2 given in... -
不知道你是怎么测试的,但既然你有兴趣,这里是my demo。
-
使用这个正则表达式而不是
disable/enable the form element,如果它设置为匹配/,你将得到to disable/enable the form element。这对你来说是个问题吗?