Multiple strpos possible?

1.5k views Asked by At

I'm trying to see if my string contains { and : and } if so returns true, but I'm missing something here.

$string = "{12345:98765}";

if(strpos($string,'{*:*}')== true) {

echo "string is good";

}

Ideas?

3

There are 3 answers

0
Toto On BEST ANSWER

How about:

if (preg_match('/\{.*?:.*?\}/', $string)) {
    echo 'string is good.';
}

Where:

/
  \{    : openning curly brace (must be escaped, it' a special char in regex)
  .*?   : 0 or more any char (non greeddy)
  :     : semicolon
  .*?   : 0 or more any char (non greeddy)
  \}    : closing curly brace (must be escaped, it' a special char in regex)
/
0
AudioBubble On
if (strpos($string,'{') !== false && strpos($string,'}') !== false) {
    echo "string is good";
}
0
ksbg On

strpos does not accept regular expressions, and it does not allow you to look for multiple needles in one statement.

Furthermore your regular expression won't work. It would need to look something like this:

{\d+:\d+}

That is if you're only dealing with digits. Replace \d with \w if it could be letters OR digits, or replace it with . if it could be any character. The + means one or more characters. Replace it with * if there could be zero or more characters surrounded by the curly brackets.

if(preg_match('/{\d+:\d+}/', $string)) {
    echo 'string is good.';
}