简体   繁体   中英

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. 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. 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.

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

正则表达式可视化

Debuggex Demo


preg_replace('/<li\b[^>]*>\K[^<:]+(?=:)/i', '<strong>$0</strong>', $str);

PHP Demo

虽然您应该避免像这样解析和操作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 ). The \\1 part will insert the selected (see "()") part back to the expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM