Valky
Valky

Reputation: 1866

How to replace "match_expression\n" with preg_replace or other?

I wonder how to replace those matches [/img]\n (\n : new line) by [/img], in a string.

I tried each of the following

$string = preg_replace("#[/img]\n#","[/img]",$string);
$string = preg_replace("/\[\/img\]\\n/","[/img]",$string);
$string = preg_replace("/\[\/img\]\n/si","[/img]",$string);

But nothing works...

$string = preg_replace("\n","Test",$string);

Works fine without the [/img] search.

I don't understand why I can't make it work.

Example

[img=y40h3inre6]Stock options[/img]

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Should become the following :

[img=y40h3inre6]Stock options[/img]
Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Upvotes: 0

Views: 76

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

Do you try :

$string = preg_replace('~\[/img]\s++~', "[/img]\n", $string);

Or this

$string = preg_replace('~\[/img]\K\s++~', "\n", $string);

\n is for newline, but if you want match the string '\n' you must use '\\\n' instead in the pattern.

As notice Rikesh the new lines can be different on some systems (\n, \r\n, \n\r)

Upvotes: 1

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

You can try it with str_replace

echo $string = str_replace('[/img]\n',"[/img]",'abcd[/img]\nabcd[/img]\n');

Output

abcd[/img]abcd[/img]

Codepad

Upvotes: 0

Related Questions