Keerthi
Keerthi

Reputation: 31

reg expression - replace text with new line for all occurances - php

I am trying to replace "XYZ" with "\n" newline using regex. but i am not succeeded. Please check the below code and help me out.

$epText = "this is for text |XYZ and |XYZ and XYZ";
$find = '|XYZ';
$replace = '\n';
$epFormatedText = preg_replace_callback(
    '/{{.+?}}/',
    function($match) use ($find, $replace) {
        return str_replace($find, $replace, $match[0]);
    },
    $epText
  );
 echo $epFormatedText;

But it is show original text. no action is performed. Please help on this.

Upvotes: 1

Views: 62

Answers (4)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

You're doing it in a wrong way you only need preg_replace over simply like as

$epText = "this is for text |XYZ and |XYZ and XYZ";
$find = '|XYZ';
$replace = '\n';

echo preg_replace("/\B" . preg_quote($find) . "\b/","\n",$epText);

Note : Take care of using quotes over here.

Demo

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

The reason is that you use single quotes around \n in $replace. That way, \n is treated as a literal \ + n characters.

As for regex, I suggest using (?<!\w) and (?!\w) look-arounds since you are looking to match whole words, not parts of other longer words (judging by your example).

As the input ($find) can contain special regex metacharacters you need to use preg_quote to escape those symbols.

Here is your fixed code:

$epText = "this is for text |XYZ and |XYZ and XYZ";
$find = '|XYZ';
$replace = "\n";
$epFormatedText = preg_replace(
    "/(?<!\\w)" . preg_quote($find) . "(?!\\w)/",
    $replace,
    $epText
  );
 echo $epFormatedText;

See IDEONE demo

Upvotes: 1

Sandeep Nambiar
Sandeep Nambiar

Reputation: 1676

Try this

echo  preg_replace('/XYZ/', '<br>', $epText);

Upvotes: 0

Professor Abronsius
Professor Abronsius

Reputation: 33813

There is no need for such a complicated function when preg_replace should do what you need.

$epText = "this is for text XYZ and XYZ and XYZ";
$replaced = preg_replace('@XYZ@',"\n",$epText);

echo '<textarea>', $replaced ,'</textarea>';

Upvotes: 0

Related Questions