Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/237.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP preg_match获取2个字符之间的字符串 请考虑此字符串: $string = 'hello world /foo bar/';_Php_Regex_Preg Match - Fatal编程技术网

PHP preg_match获取2个字符之间的字符串 请考虑此字符串: $string = 'hello world /foo bar/';

PHP preg_match获取2个字符之间的字符串 请考虑此字符串: $string = 'hello world /foo bar/';,php,regex,preg-match,Php,Regex,Preg Match,我希望得到的最终结果是: $result1 = 'hello world'; $result2 = 'foo bar'; 我所尝试的: preg_match('/\/(.*?)\//', $string, $match); 麻烦的是这只返回“foo-bar”而不是“hello-world”。我可能可以从原始字符串中去掉“/foo-bar/”,但在我的实际用例中,这需要额外的两个步骤 $result = explode("/", $string); 导致 $result[0] == 'hel

我希望得到的最终结果是:

$result1 = 'hello world';
$result2 = 'foo bar';
我所尝试的:

preg_match('/\/(.*?)\//', $string, $match);
麻烦的是这只返回“foo-bar”而不是“hello-world”。我可能可以从原始字符串中去掉“/foo-bar/”,但在我的实际用例中,这需要额外的两个步骤

$result = explode("/", $string);
导致

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

您可能需要替换hello world中的空格。此处的详细信息:

正则表达式只匹配您告诉它要匹配的内容。因此,您需要让它匹配所有内容,包括
/
s,然后对
/
s进行分组

这应该做到:

$string = 'hello world /foo bar/';
preg_match('~(.+?)\h*/(.*?)/~', $string, $match);
print_r($match);
PHP演示:
Regex101:(分隔符转义,在PHP使用中更改了分隔符)


0
索引是找到的所有内容,
1
第一组,
2
第二组。所以在
/
之间是
$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

explode(“/”,$string)有什么问题?可能重复您尝试过什么吗?@Tuesdave该线程没有回答我的问题您是在寻找如何使用正则表达式还是仅仅是如何使用正则表达式。有关正则表达式不起作用的原因,请参见,。这将导致:$result[1]=='foobar/';另外,它也不适用于我的实际用例。嗯,非常确定它将是$result[1]='foo bar',并且$result[2]将是一个空字符串,因为在任何情况下,all/are replacedOk,explode都不适用于我的实际用例,因为数组项的数量很重要,而且它不是常量。