2

I'm trying to preg_match_all a string that I'm getting from user input that has an apostrophe in it. First I tested it out on a regular string to see if it'll match or not, and it does. However, when I tried to test it out on the same user input string, it doesn't work. I think it's because the apostrophe in the user input gets escaped, before I compared them.

$temp1 = "I'm a person.";

preg_match_all('/I\'m\s+(.+)/i', $temp1, $matches);
$temp1 = $matches[1][0];
echo $temp1;

output : a person.

However, since I'm getting $temp from user input and escaping the apostrophe, it escapes the apostrophe when it takes it out, and therefore it doesn't match:

$temp2 = "I\'m a person.";

preg_match_all('/I\'m\s+(.+)/i', $temp2, $matches);
$temp2 = $matches[1][0];
echo $temp2;

output : null.

How do I fix this? Thanks.

1 Answer 1

1

You can use:

preg_match_all('/I\\\\\'m\s+(.+)/i', $temp2, $matches);
echo $matches[1][0];

Output:

a person.

Use \\\\ to match a single backslash in input.

1
  • 1
    I have to say that all these escaping is kind of weird, lol. but it works. thanks.
    – jessica
    Aug 26, 2015 at 15:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.