Avatar of tjyoung
tjyoung
 asked on

How to escape # using preg_match. Simple backslash doesn't seem to work?

Hi,
I'm trying to test if a string matches the word #yesterday (including the pound sign). I am finding if I don't have the pound sign in and the $body equals 'yesterday' works fine. But with the # sign, doesn't.

if( preg_match('/^(#yesterday)$/i', $body) ){

How (I'm stuck in 5.2+ php) can I see if the string is yesterday with the pound sign?

Thanks,
PHP

Avatar of undefined
Last Comment
Ray Paseur

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Ray Paseur

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
tjyoung

ASKER
I'm using Twilio and when an incoming text contains certain keywords ie: #today, #yesterday, #week or #month, I'm responding back with how many car deals were done in that period of time. So the user texts just the one word with the pound sign in front so my app knows its an instruction and not just a 'word' like yesterday.

I test the $to number to be sure its an admin phone number, than check the
$body = $_REQUEST['Body']; against those keywords.

Kind of like:
if( preg_match('/^(today)$/i', $body) ){
send back deals today
} else if if( preg_match('/^(yesterday)$/i', $body) ){
send back yesterdays deal count
} else {
do whatever
}

Works fine until I add in the # pound sign.

I tried placing the slash but didn't seem to work:
if( preg_match('/^(/#yesterday$/i', $body) ){

just didn't return anything.
Ray Paseur

I understand the issue; I just need to see the actual test data.  You can get this with var_dump().  Then use view source and copy/paste the information here.  When your regex has the ^ and $ at the beginning and end, you're telling the engine to evaluate the entire string.  If there are any other characters, even invisible whitespace, the match will fail.

Philosophy on why the test data matters (much more than the failing code):
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_7830-A-Quick-Tour-of-Test-Driven-Development.html
tjyoung

ASKER
That worked perfectly as the how to example. Thanks again.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Ray Paseur

Great!  Thanks for the points and thanks for using EE, ~Ray