Reputation: 1569
I'm trying to write what should be a fairly simple regex for a PHP script to match tag:
followed by a word in double quotes. I want it to return just the value inside the quotes, minus the quotes themselves (tag:"whatever"
returns whatever
).
I have a search box on a page which submits the form data (via GET, if that matters) to itself, and runs a PHP script on it. This is what happens inside the script:
$q = urldecode(filter_input(INPUT_GET, 'q', FILTER_SANITIZE_STRING));
preg_match_all("/tag:\"([\w]+)\"/", $q, $tags);
I want it to match something like tag:"this"
, but when I search for that, I get no matches:
//print_r($tags) yields:
Array
(
[0] => Array
(
)
[1] => Array
(
)
)
I figured it might be an escaping issue, so I also tried
$q = stripslashes(urldecode(filter_input(INPUT_GET, 'q', FILTER_SANITIZE_STRING)));
preg_match_all("/tag:\"([\w]+)\"/", $q, $tags);
and
$q = urldecode(filter_input(INPUT_GET, 'q', FILTER_SANITIZE_STRING));
preg_match_all("/tag:\\\"([\w]+)\\\"/", $q, $tags);
Both of these return the same array of two empty arrays.
In desperation I even tried it with single quotes (and searching for tag:'this'
), which I didn't need to escape, but this also returned nothing:
$q = urldecode(filter_input(INPUT_GET, 'q', FILTER_SANITIZE_STRING));
preg_match_all("/tag:'([\w]+)'/", $q, $tags);
Removing the quotes, incidentally, makes it work fine:
//searching for tag:something with preg_match_all("/tag:([\w]+)/", $q, $tags); yields:
Array
(
[0] => Array
(
[0] => tag:something
)
[1] => Array
(
[0] => something
)
)
I'm almost certain I'm making a really foolish mistake, but stare at it as I might, I can't figure out what. I have tried searching for it, but was unable to find anyone with the same problem. This further leads me to think the problem is trivial, and that I'm being dim. Help!
Upvotes: 1
Views: 1757
Reputation: 174957
Use the following:
preg_match('|tag:"(\w+)"|', $str, $results);
When using single quotes in PHP, it saves you the need to escape the double quotes, thus saving you the confusion over what to escape and what is a character in RegEx.
Upvotes: 1