[英]Using preg_replace to “update” searched string
So i have this string: 所以我有这个字符串:
$str='<li>Smartphone: Da</li>
<li>Touchscreen: Da</li>
<li>Tastatura QWERTY: Nu</li>
<li>Tip tastatura: Standard</li>
<li>Rezolutie senzor (Mp): 5</li>
<li>SAR (W/kg ): 1.17</li>';
And what i am trying to do is to add some 'strong' tags to the word between li tags and the ':' character. 而我想要做的是在li标签和':'字符之间的单词中添加一些“强”标签。 I tried getting all the wanted words in an array with: 我尝试在数组中获取所有想要的单词:
preg_match_all('/<li>(.*?):/', $str, $matches);
and then trying to transform them from there but it didn't help me so much. 然后试图从那里改造它们,但它对我没那么帮助。 So now i am trying to use preg_replace but i don't want to give a substitute word as a parameter because it differs from one li to another. 所以现在我正在尝试使用preg_replace但我不想给替换单词作为参数,因为它不同于一个li。 In other words i want to do something like this: 换句话说,我想做这样的事情:
preg_replace('/<li>(.*?):/',"<strong>'/<li>(.*?):/'</strong>",$str);
So i want to search for the text between li tags and ':' and then put strong tags before and after in order for it to become bold. 所以我想在li标签和':'之间搜索文本,然后在前后放置强标签,以使其变为粗体。
Sorry if my explanation was bad but i fairly new to regular expressions and don't really know the vocabulary. 很抱歉,如果我的解释很糟糕,但我对正则表达式相当新,并且不太了解词汇量。 Thanks in advance. 提前致谢。
/<li\b[^>]*>\K[^<:]+(?=:)/i
preg_replace('/<li\b[^>]*>\K[^<:]+(?=:)/i', '<strong>$0</strong>', $str);
虽然您应该避免像这样解析和操作HTML,但是如果您知道使用正则表达式进行HTML解析的所有问题并且仍然想要使用正则表达式:
preg_replace('/(?<=<li>)(.+?)(?=:)/', '<strong>$1</strong>', $str);
$str = preg_replace('/(?<=<li>)([^:]*)/', '<strong>$1</strong>', $str);
print_r($str);
Output: 输出:
<li><strong>Smartphone</strong>: Da</li>
<li><strong>Touchscreen</strong>: Da</li>
<li><strong>Tastatura QWERTY</strong>: Nu</li>
<li><strong>Tip tastatura</strong>: Standard</li>
<li><strong>Rezolutie senzor (Mp)</strong>: 5</li>
<li><strong>SAR (W/kg )</strong>: 1.17</li>
The replacement expression you were looking for is: 您正在寻找的替换表达式是:
preg_replace('/<li>([^:]*):/','<li><strong>\1</strong>:',$str);
The [^:]*
part matches all characters which are not ":" (otherwise the regular expression would be "greedy", see: http://www.regular-expressions.info/repeat.html#greedy ). [^:]*
部分匹配所有不是“:”的字符(否则正则表达式将是“贪婪的”,请参阅: http : //www.regular-expressions.info/repeat.html#greedy )。 The \\1 part will insert the selected (see "()") part back to the expression. \\ 1部分将所选(见“()”)部分插回到表达式中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.