-3

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.

chris85
  • 23,846
  • 7
  • 34
  • 51
Mike Feng
  • 803
  • 2
  • 9
  • 19

3 Answers3

2
$result = explode("/", $string);

results in

$result[0] == 'hello world ';
$result[1] == 'foo bar';

You might want to replace the space in hello world. More info here: http://php.net/manual/de/function.explode.php

chris85
  • 23,846
  • 7
  • 34
  • 51
MarkHim
  • 5,686
  • 5
  • 32
  • 64
  • This will result in: $result[1] == 'foo bar/'; Also it's not applicable to my real use case. – Mike Feng Jan 25 '16 at 17:11
  • 3
    huh, pretty sure it will be $result[1] == 'foo bar' and $result[2] will be an empty string, since all / are replaced – MarkHim Jan 25 '16 at 17:14
  • Ok in any case, explode is not applicable in my real use case because the number of array items matter and it's not constant. – Mike Feng Jan 25 '16 at 17:20
2

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).

chris85
  • 23,846
  • 7
  • 34
  • 51
0

To solve this conversion issue, use below code.

$string      = 'hello world /foo bar/';
$returnValue =  str_replace(' /', '/', $string);
$result      =  explode("/", $returnValue);

If you want to print it, put below lines in your code.

echo $pieces[0]; // hello world
echo $pieces[1]; // foo bar

https://eval.in/507650

AsgarAli
  • 2,201
  • 1
  • 20
  • 32