Preg_match returns null when looking for escaped quotes
I am fetching a string from my Wordpress database; the string I get is a textbox where the Wordpress gallery can be added. Some example strings are as follows:
<p>test</p><p>[gallery columns=\"2\" ids=\"705,729\"]</p>
<p>[gallery columns=\"2\" ids=\"696,694\"]</p>
<p>test</p>
I want to get the numbers that are in the field ids=\"x,x\"
.
I have the following code:
for ($i = 1; $i<5; $i++) {
$result = get_ids_per_category($i, getReferencesMapId());
${"idArray".$i} = array();
foreach ($result as $res) {
$subject = $res->description;
$pattern = "/\[(.*?)\]/";
preg_match($pattern,$subject,$matches);
if ($matches[1]) {
$subject2 = $matches[1];
$pattern2 = '/ids=\\"(.*)\\"/';
preg_match($pattern2, $subject2, $matches2);
array_push( ${"idArray".$i}, $matches2);
}
}
if (!empty(${"idArray".$i})) {
${"finalArray".$i} = array();
foreach (${"idArray".$i} as $arr) {
$newarray = explode(",",$arr[1]);
foreach ($newarray as $item) {
array_push( ${"finalArray".$i}, $item);
}
}
}
}
If I call var_dump($subject2)
, the following results are returned:
\page-referentiemap.php:58:string 'gallery columns=\"2\" ids=\"477,476\"' (length=37)
\page-referentiemap.php:58:string 'gallery columns=\"1\" ids=\"690\"' (length=33)
\page-referentiemap.php:58:string 'gallery ids=\"688,689,690\"' (length=27)
\page-referentiemap.php:58:string 'gallery columns=\"2\" ids=\"697,698,699\"' (length=41)
\page-referentiemap.php:58:string 'gallery ids=\"702,701,703\"' (length=27)
\page-referentiemap.php:58:string 'gallery columns=\"2\" ids=\"696,694\"' (length=37)
So far so good, but then the line is where I create my regex like this:
preg_match($pattern2, $subject2, $matches2);
Will always return null in $matches2
.
I can't remember how I have changed the code in the last couple of weeks when it actually worked. Can anyone tell me what I am missing?
source to share
You need to escape the backslash twice. Once for PHP and once for PCRE. Try this instead:
$pattern2 = '/ids=\\\\"(.*)\\\\"/';
Although it really looks like you could make this code a lot simpler. Obviously I can't fully test, but it looks like this should work:
<?php
$ids = [];
for ($i = 1; $i<5; $i++) {
$result = get_ids_per_category($i, getReferencesMapId());
foreach ($result as $res) {
$subject = $res->description;
$pattern = '/\[.*?\\bids=\\\\"(\d+),(\d+)\\\\".*?\]/';
if (preg_match($pattern,$subject,$matches)) {
$ids[$i][] = [$matches[1], $matches[2]];
}
}
}
print_r($ids);
You want to stay away from dynamic variable names unless you have a compelling reason. Arrays are almost always preferred.
source to share