Reputation: 31
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
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.
Upvotes: 1
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
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