Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is equivalent of =~ of ruby in php?

I am a Rubyist trying to implement some of my code in PHP and not able to get the equivalent PHP code for this particular def.Can anyone help me out.Thanks in advance.

def check_condition(str)
  str =~ SOME_REGEX
end
like image 410
vivekporwal04 Avatar asked Jun 11 '13 07:06

vivekporwal04


3 Answers

In PHP it looks like:

function check_condition($str) {
    return preg_match(SOME_REGEX, $str);
}

Unfortunately there is no regex-match operator in PHP unlike some other languages. You'll have to call a function. Follow the manual of preg_match() and the manual page about the so called perl compatible regular expresssions (preg) in general.


Something additional. After reading the manual page of preg_match you know that the method returns an integer, the number of matches found. As the method returns after the first match this can be only 0 or 1. As of the loose typing system of PHP this would be good for using it in loose comparisons like:

if(check_condition($str)) { ....
if(check_condition($str) == true)  { ...

But it would not work in a strict comparison:

if(check_condition($str) === true) { ...

Therefore it would be a good idea to cast the return value of preg_match:

function check_condition($str) {
    return (boolean) preg_match(SOME_REGEX, $str);
}

Update

I have thought a little bit about my last suggestion and I see a problem with this. preg_match() will return an integer if all is working fine but boolean FALSE if an error occurs. For example because of a syntax error in the regex pattern. Therefore you will be not aware of errors if you are just casting to boolean. I would use exceptions to show that an error was happening:

function check_condition($str) {
    $ret = preg_match(SOME_REGEX, $str);
    if($ret === FALSE) {
        $error = error_get_last();
        throw new Exception($error['message']);
    }

    return (boolean) $ret;
}
like image 177
hek2mgl Avatar answered Nov 07 '22 05:11

hek2mgl


Have a look at preg_match:

if (preg_match('/regex/', $string) {
    return 1;
}
like image 5
Toto Avatar answered Nov 07 '22 05:11

Toto


Isn't it preg_match?

function check_condition($str) {
    return preg_match(SOME_REGEX,$str);
}
like image 5
Dave Chen Avatar answered Nov 07 '22 04:11

Dave Chen