PHP preg_match 获取 2 个字符之间的字符串
PHP preg_match getting string between 2 chars
请考虑这个字符串:
$string = 'hello world /foo bar/';
我希望得到的最终结果:
$result1 = 'hello world';
$result2 = 'foo bar';
我尝试过的:
preg_match('/\/(.*?)\//', $string, $match);
问题是这只是 return "foo bar" 而不是 "hello world"。我可能可以从原始字符串中删除“/foo bar/”,但在我的实际用例中需要额外的 2 个步骤。
$result = explode("/", $string);
结果
$result[0] == 'hello world ';
$result[1] == 'foo bar';
您可能想要替换 hello world 中的 space。更多信息在这里:http://php.net/manual/de/function.explode.php
正则表达式只匹配您告诉它匹配的内容。所以你需要让它匹配包括 /
s 在内的所有内容,然后将 /
s.
分组
应该这样做:
$string = 'hello world /foo bar/';
preg_match('~(.+?)\h*/(.*?)/~', $string, $match);
print_r($match);
PHP 演示:https://eval.in/507636
Regex101:https://regex101.com/r/oL5sX9/1(分隔符已转义,在 PHP 用法中更改了分隔符)
0
索引是找到的所有内容,1
第一组,2
第二组。所以在 /
s 之间是 $match[2]
; hello world
是 $match[1]
。 \h
是 /
之前的任何水平空格,如果您希望在第一组中删除 \h*
。 .
将占空白(除非用 s
修饰符指定,否则不包括新行)。
要解决此转换问题,请使用以下代码。
$string = 'hello world /foo bar/';
$returnValue = str_replace(' /', '/', $string);
$result = explode("/", $returnValue);
如果您想打印它,请在您的代码中添加以下行。
echo $pieces[0]; // hello world
echo $pieces[1]; // foo bar
请考虑这个字符串:
$string = 'hello world /foo bar/';
我希望得到的最终结果:
$result1 = 'hello world';
$result2 = 'foo bar';
我尝试过的:
preg_match('/\/(.*?)\//', $string, $match);
问题是这只是 return "foo bar" 而不是 "hello world"。我可能可以从原始字符串中删除“/foo bar/”,但在我的实际用例中需要额外的 2 个步骤。
$result = explode("/", $string);
结果
$result[0] == 'hello world ';
$result[1] == 'foo bar';
您可能想要替换 hello world 中的 space。更多信息在这里:http://php.net/manual/de/function.explode.php
正则表达式只匹配您告诉它匹配的内容。所以你需要让它匹配包括 /
s 在内的所有内容,然后将 /
s.
应该这样做:
$string = 'hello world /foo bar/';
preg_match('~(.+?)\h*/(.*?)/~', $string, $match);
print_r($match);
PHP 演示:https://eval.in/507636
Regex101:https://regex101.com/r/oL5sX9/1(分隔符已转义,在 PHP 用法中更改了分隔符)
0
索引是找到的所有内容,1
第一组,2
第二组。所以在 /
s 之间是 $match[2]
; hello world
是 $match[1]
。 \h
是 /
之前的任何水平空格,如果您希望在第一组中删除 \h*
。 .
将占空白(除非用 s
修饰符指定,否则不包括新行)。
要解决此转换问题,请使用以下代码。
$string = 'hello world /foo bar/';
$returnValue = str_replace(' /', '/', $string);
$result = explode("/", $returnValue);
如果您想打印它,请在您的代码中添加以下行。
echo $pieces[0]; // hello world
echo $pieces[1]; // foo bar