简体   繁体   中英

I want replace pattern that is matched

i am trying to replace string that is matched see example bellow

<?php
    $str="this is going to bold [[this]]";
    echo preg_replace("/[[(.*)]]+/i","<b>$1</b>",$str);
?>

So the output will look like this

this is going to bold this

Edit:

<?php
    $str="bhai bhai *that* -wow- perfect";
    $find[0]="/*(.+)*/i";
    $find[1]="/-(.+)-/i";
    $rep[0]="<b>$1</b>";
    $rep[1]="<i>$1</i>";
    echo preg_replace($find,$rep,$str);
?>

This is showing warning

Warning: preg_replace() [function.preg-replace]: Compilation failed: nothing to repeat at offset 0 in C:\\xampp\\htdocs\\page.php on line 7

Try this :

<?php
    $str="this is going to bold [[this]]";
    echo preg_replace("/\[\[(.+)\]\]+/i","<b>$1</b>",$str);
?>

Output :

this is going to bold 大胆


Hint :

[ and ] characters are considered special , so you'll have to escape them (like : \\[ , \\] ).


UPDATE :


<?php
    $str="bhai bhai *that* -wow- perfect";
    $find[0]="/\*(.+)\*/i";
    $find[1]="/\-(.+)\-/i";
    $rep[0]="<b>$1</b>";
    $rep[1]="<i>$1</i>";
    echo preg_replace($find,$rep,$str);
?>

Try this on for size

<?php
    $str="this is going to bold [[this]]";
    echo preg_replace("/(?:\[\[)(.*?)(?:\]\])/i","<b>$1</b>",$str);
?>

You need to escape the square brackets in your regular expression. The final expression should look something like this:

echo preg_replace('/\[\[(.*?)\]\]/im', '<b>$1</b>', $str);

The square brackets are special characters used for defining a set of characters and thus must be escaped if you wish to match them literally.

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