Search code examples
phpstringvalidationends-with

Check if string ends with a specified substring


I have a string and I need to see if it contains the following "_archived".

I was using the following:

preg_match('(.*)_archived$',$string);

but get:

Warning: preg_match() [function.preg-match]: Unknown modifier '_' in /home/storrec/classes/class.main.php on line 70

I am new to Regular Expressions so this is probably very easy.

Or should I be using something a lot simpler like

strstr($string, "_archived");

Solution

  • strstr is enough in this case, but to solve your problem, you need to add delimiters to your regex. A delimiter is a special character that starts and ends the regex, like so:

    preg_match('/_archived/',$string);
    

    The delimiter can be a lot of different characters, but usual choices are /, # and !. From the PHP manual:

    Any character can be used for delimiter as long as it's not alphanumeric, backslash (), or the null byte. If the delimiter character has to be used in the expression itself, it needs to be escaped by backslash. Since PHP 4.0.4, you can also use Perl-style (), {}, [], and <> matching delimiters.

    Read all about PHP regular expression syntax here.

    You can see some examples of valid (and invalid) patterns in the PHP manual here.