user1331534
user1331534

Reputation:

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

Upvotes: 2

Views: 101

Answers (3)

Dr.Kameleon
Dr.Kameleon

Reputation: 22820

Try this :

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

Output :

this is going to bold this


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);
?>

Upvotes: 4

xenon
xenon

Reputation: 1425

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.

Upvotes: 0

Josh Davenport-Smith
Josh Davenport-Smith

Reputation: 5511

Try this on for size

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

Upvotes: 0

Related Questions