wrap -tag around first word of string with preg_replace

后端 未结 3 1937
既然无缘
既然无缘 2021-01-13 20:07

My problem is, that this:

preg_replace(\'/(?<=\\>)\\b\\w*\\b|^\\w*\\b/\', \'$&\', $string);

Does not work and

相关标签:
3条回答
  • 2021-01-13 20:14

    Try with this instead

    preg_replace('/(?<=\>)\b\w*\b|^\w*\b/', '<b>$0</b>', $string);
    

    $0 means it will become the first thing matched in your regex, $1 will become the second etc.

    You could also use back-references; \0 gets the first thing matched back from where you are, \1 gets the second thing matched back etc. More Info

    0 讨论(0)
  • 2021-01-13 20:34

    You need to put a number after $ to refer to grouped part of the regex.Here it would be first group , hence 0. Working example here : http://codepad.org/4V7GWdja

    <?php
    
    $string = "an example";
    $string = preg_replace('/(?<=\>)\b(\w*)\b|^\w*\b/', '<b>$0</b>', $string);
    var_dump($string);
    
    ?>
    
    0 讨论(0)
  • 2021-01-13 20:36
    $string = 'an example';
    echo preg_replace('/^\b(.+?)\b/i', '<b>$1</b>', $string);
    
    // <b>an</b> example
    
    0 讨论(0)
提交回复
热议问题