Grant
Grant

Reputation: 29

What is the PHP equivalent to Perl's regex alternations?

I'm converting one of my old Perl programs to PHP, but having trouble with PHP's string handling in comparison to Perl.

In Perl, if I wanted to find out if $string contained this, that or the_other I could use:

if ($string =~ /this|that|the_other/){do something here}

Is there an equivalent in PHP?

Upvotes: 2

Views: 511

Answers (3)

Felix Kling
Felix Kling

Reputation: 816462

You can either use a regular expression (e.g. preg_match):

if(preg_match('/this|that|the_other/', $string))

or make it explicit (e.g. strstr):

if(strstr($string, 'this') || strstr($string, 'that') || strstr($string, 'the_other'))

Upvotes: 2

codaddict
codaddict

Reputation: 455092

In PHP you can use preg_match function as:

if( preg_match('/this|that|the_other/',$string) ) {
  // do something here.
}

Upvotes: 1

friedo
friedo

Reputation: 66968

You can use PHP's preg_match function for a simple regex test.

if ( preg_match( "/this|that|the_other/", $string ) ) { 
    ...
}

Upvotes: 1

Related Questions