WP
36 0
Asked
Updated
Viewed
16.1k 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
1

2 Answers

  • Votes
  • Oldest
  • Latest
BO
466 10
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
}
?>
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
}
add a comment
0