Why are escaped characters read from database, using PHP, displaying as normal text on output during regular expression replace?
I am trying to store regular expression search and substitution strings in a database. At runtime, I read the database, placing the strings into arrays, and then use the PHP preg_replace() method to update large strings written by users with fixes that my client wants.
Here is a sample string pair I am using:
Search string: /([^\r\n+])(\[url)/i
$1\n\n$2
If I place the string in code like this:
preg_replace("/([^\r\n]+)(\[url)/i", "$1\r\n\r\n$2", ProcessString);
Everything works beautifully. This finds instances of a bbCode tag "[url" that does not have a carriage-return/linefeed combination directly in front of it and places that in front of the "[url" tag.
However, when I run the code as I stated using strings from the database (MySql), the "\r\n\r\n" print literals instead of actually creating carriage-return line feeds. The strings are displayed in a "textarea" tag in HTML.
I have looked at the difference between single and quoted strings and my problem would seem to be this, I am assuming? Thinking that the problem is that the strings coming from the database or inserted into the array I'm looping through are created as single-quoted strings, I tried this:
preg_replace($findKey, "{$replaceValue}", ProcessString);
Where $replaceValue = the string '$1\r\n\r\n$2' (again, I am assuming that reading from the database and/or placing the value into an array (mysql_fetch_assoc($result)) is placing the string value into a single-quoted string and th开发者_Python百科erefore the escaped characters are printing as literals instead of the characters the escaped characters actually represent. However, this did not work.
Here is the code I'm using to insert into the database:
INSERT INTO ISG_TCS_Replacements (FindPhrase, ReplacePhrase, ReplacementGroupID, Description, IsRegEx, IsActive, ProcessGroup, ProcessSequence)
VALUES ("/([^\\r\\n]+)(\\[url)/i","$1\\r\\n\\r\\n$2", 0, "Add a new line after [url] tags that are not on a new line currently.", 1, 1, 0, 1);
The fields are varchar(100).
The issue is that \r\n
escapes only work in double quoted strings.
print "\r\n";
Whereas your database usage is likely akin to:
$replaceValue = '\r\n';
print "{$replaceValue}"; // uses the literal character string
You are inserting your replacement string with single quotes into the DB. Otherwise you would get the the actual linebreaks back. Mysql does escape them while inserting, but you always get the original string data back.
Reading from a MySQL TEXT/CHAR column is no different than reading from files really. Check your database with mysqladmin, if you see the literal \r\n
then there is your problem.
(A literal '\r\n'
btw works in the regex, but not in the replacement string.)
Something else. ([^\r\n+])
is probably meant to be ([^\r\n]+)
. The quantifier must be outside of the character class.
精彩评论