我想問題,使周圍一個特定的字符串大膽兩個字像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’,因爲
... 和匹配字之後...字 邊界陣列 ... 禁用/啓用的形式元件 ...
另外一個缺點這個解決方案是它只搜索兩個空格之間的字符串。這可以修改,以便它搜索任何字符串?
最後,可能我們就可能找到搜索的數量進行限制,這樣,如果是爲字符串再次搜索「的」在前文中,我將限制設置爲一個我應該只得到
... 和匹配字後...
不知道,但也許,[''/.*?\b((?:\w+[\p{Zs}\p{P}]+){0,2}the(?:[\p {ZS} \ p {p}] + \ W +){0,2} \ b)中[^!?*/is''](https://regex101.com/r/wW9dF0/3)。或([:。*?\ b +({:\ w +){0,2} \ b)[ ^。!?] *'](https://regex101.com/r/wW9dF0/1)。 –
將搜索限制爲1是使用'preg_match'完成的。 –
@stribizhev,無論您的建議給予'警告:的preg_replace()預計至少3個參數,2給出...' – user3741635