4

I have a string returning a URL and need to figure out how to use if and regex to do something whenever the returned URL contains a question mark.

So when $url is http://somedomain.com/?p=34325&blahblahblah

IF the $url contains "?p=" (and discarding everything else) then exit, otherwise do something


Any help?
Many thanks

3 Answers 3

9

You don't need a regex to match a simple string:

if (strpos($url, '?p=') !== false) {
   exit;
}
//do something

If you really wanted to use a regex:

if (preg_match('/\?p=/', $url)) {
Sign up to request clarification or add additional context in comments.

Comments

4

Don't use regex for this. You do not need the power of regular pattern matching. Just use strstr:

if(strstr($url, 'p=?')){
    exit;
}

// Do other stuff

3 Comments

Ok. Worked a treat. Thanks very much for your help!
@WendiT It's an X/Y question. I answered "How to check for a question mark in PHP string?", because the best answer to "How to check for a question mark in PHP string using regex?" is simply "Don't". It is incorrect to use a regular expression for such a task in PHP.
ok clear. Do I need to use preg_match for multiple needles 5-6 needles) or is there a better solution?
0

if (preg_match("/(\?p=)/", $url)) {

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.