regex - reg expression - replace text with new line for all occurances - php -
i trying replace "xyz" "\n" newline using regex. not succeeded. please check below code , me out.
$eptext = "this text |xyz , |xyz , 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 show original text. no action performed. please on this.
the reason use single quotes around \n
in $replace
. way, \n
treated literal \
+ n
characters.
as regex, suggest using (?<!\w)
, (?!\w)
look-arounds since looking match whole words, not parts of other longer words (judging example).
as input ($find
) can contain special regex metacharacters need use preg_quote
escape symbols.
here fixed code:
$eptext = "this text |xyz , |xyz , xyz"; $find = '|xyz'; $replace = "\n"; $epformatedtext = preg_replace( "/(?<!\\w)" . preg_quote($find) . "(?!\\w)/", $replace, $eptext ); echo $epformatedtext;
see ideone demo
Comments
Post a Comment