<?php
$string = '\n \n \n \n';
$patterns = '/\n/';
$replacements = '/\\n/';
echo preg_replace($patterns, $replacements, $string);
?>
This segment of code does not seem to work, Any suggestions on why this is happening. It does not echo anything at all. I can get it working with ereg but wanted to change over to preg.
Many issues here…
Are you trying to create a string made of new-line characters?
'\n \n \n \n'is not the way, it does not works. Use"\n \n \n \n"and read the PHP official manual about strings here.Your pattern is not escaped correctly. Try
'/\\n/', anyway I’m not sure your version does not work.What’s the reason for your
'/\\n/'replacement? Please provide an example of input string and desired output.If you are trying to escape strings to save them in a database, you are completely on the wrong way. Google for php database escaping, and read about
mysql_escape_string()(or equivalent ones if you are not using MySQL). There are functions to do it, and you have to use them. You cannot rely (or there is no reason to do it) on custom made functions using regular expressions.