WP
24 0
Asked
Updated
Viewed
9.8k times

I need to detect if a colon : is in a string. How can I match or negatively match a colon using regular expressions with preg_match?

In my case I need to negatively match as there must not be a colon in order to do something:

if(! preg_match("/(:)+/",$strdomaine)) {
    //If no colon found do something
}
else {
    //colon found
}

I have tried various regex versions but cannot seem to do it. I have read that the the colon is special, could be a delimiter, etc.

Does this mean there is a special way to detect the colon?

add a comment
0

2 Answers

  • Votes
  • Oldest
  • Latest
BO
60 2
Answered
Updated

How about strpos? No need for regex here.

<?php

if(strpos($strdomaine, ':') == false)
{
     // The colon was not found in the string
}
else
{
    // The colon WAS found in the string
}
?>
  • 0
    +1 for not using a regex just to detect the presence of a single character. — spork
add a comment
1
Answered
Updated

Just put a backslash in front of the colon so that it looks like \:, or in case you don't know exactly what to escape you could always run the string through preq_quote first and it will escape everything for you. With that said your code would then look like this:

if(! preg_match("/\:/",$strdomaine)) {
    //If no colon found do something
}
else {
    //colon found
}
  • 0
    That worked quite nice. — wpas
add a comment
0