简体   繁体   中英

How do I print and store regex (Regular Expressions) in PHP and MYSQL

I need to be able to store and echo regular expressions. In my case the user enters the regex into a form and that exact sequence of characters needs to be echo-ed to the screen sometime later. The problem is that the echo changes the characters.

So for instance I have tried this

$regex = '(?<=amount\">\$)(.*?)(?=</strong>)';

but when I echo it..

echo $regex;

I get...

((((amount\">\$)(.*?)(?=)

If I do this

$regex = htmlentities($regex);

I get this which helped with the missing part of the regex but not the multiple ((((

((((amount\">\$)(.*?)(?=</strong>

htmlspecialchars did not help either.

How do I get it to echo the variable exactly as it is written? And what would I need to do to store them in MySQL and retrieve them exactly as written?

EDIT - in response to some observations below, I add a bit more detail. This new example was done on a PHP 7.1 server in the cloud, Centos 7 rendered using Chrome.

$regex = '(?<=amount\">\$)(.*?)(?=</strong>)';

$page_elements_regex[1][0] = $regex;
$page_elements_regex[1][1] = addslashes($regex);
$page_elements_regex[1][2] = htmlspecialchars($regex);
$page_elements_regex[1][3] = htmlentities($regex);

echo "regex  " . $page_elements_regex[1][0] . "<BR>";
echo "addslashes  " . $page_elements_regex[1][1] . "<BR>";
echo "htmlspecialcharacters  " . $page_elements_regex[1][2] . "<BR>";
echo "htmlentities  " . $page_elements_regex[1][3] . "<BR>";

Results

regex ((((amount\">\$)(.*?)(?=)
addslashes ((((amount\\\">\\$)(.*?)(?=)
htmlspecialcharacters ((((amount\">\$)(.*?)(?=</strong>)
htmlentities ((((amount\">\$)(.*?)(?=</strong>)

It is also a big clue that if you take off the first ( like this

$regex = '?<=amount\">\$)(.*?)(?=</strong>)';

The result removes the first a of amount?! Is it interpreting the regex instead of echoing it?

 ?(((mount\">\$)(.*?)(?=)

I have solved it, and I feel a bit foolish about the answer. My bad.

Somewhere else in my code I had this

$regex[1] = '(?<=amount\">\$)(.*?)(?=</strong>)';
$regex[2] = '(?<=amount\">\$)(.*?)(?=</strong>)';
$regex[3] = '(?<=amount\">\$)(.*?)(?=</strong>)';

I have no idea why this gave the result it did, rather than a straight up error, but once removed it all is fine. The bottom line is that both htmlspecialcharacters and htmlentities give the right answer, Lesson learnt. Check all the code, my mistake was in the use of arrays, defining $regex as an array and a variable, not as I first thought here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM