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

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -