Search code examples
phpregexpreg-match

PHP preg_match getting string between 2 chars


Please consider this string:

$string = 'hello world /foo bar/';

The end result I wish to obtain:

$result1 = 'hello world';
$result2 = 'foo bar';

What I've tried:

preg_match('/\/(.*?)\//', $string, $match);

Trouble is this only return "foo bar" and not "hello world". I can probably strip "/foo bar/" from the original string, but in my real use case that would take additional 2 steps.


Solution

  • The regular expression only matches what you tell it to match. So you need to have it match everything including the /s and then group the /s.

    This should do it:

    $string = 'hello world /foo bar/';
    preg_match('~(.+?)\h*/(.*?)/~', $string, $match);
    print_r($match);
    

    PHP Demo: https://eval.in/507636
    Regex101: https://regex101.com/r/oL5sX9/1 (delimiters escaped, in PHP usage changed the delimiter)

    The 0 index is everything found, 1 the first group, 2 the second group. So between the /s is $match[2]; the hello world is $match[1]. The \h is any horizontal whitespace before the / if you want that in the first group remove the \h*. The . will account for whitespace (excluding new line unless specified with s modifier).