PHP preg_match 进入字符串之间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13557894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:41:00  来源:igfitidea点击:

PHP preg_match get in between string

phpregexpreg-match

提问by Kevin King

I'm trying to get the string hello world.

我正在尝试获取 string hello world

This is what I've got so far:

这是我到目前为止所得到的:

$file = "1232#hello world#";

preg_match("#1232\#(.*)\##", $file, $match)

回答by Michael Berkowski

It is recommended to use a delimiter other than #since your string contains #, and a non-greedy (.*?)to capture the characters before #. Incidentally, #does not need to be escaped in the expression if it is not also the delimiter.

建议使用分隔符而不是#因为您的字符串包含#,并且使用非贪婪(.*?)来捕获 之前的字符#。顺便说一句,#如果它不是分隔符,则不需要在表达式中进行转义。

$file = "1232#hello world#";
preg_match('/1232#(.*?)#/', $file, $match);

var_dump($match);
// Prints:
array(2) {
  [0]=>
  string(17) "1232#hello world#"
  [1]=>
  string(11) "hello world"
}

Even better is to use [^#]+(or *instead of +if characters may not be present) to match all characters up to the next #.

更好的是使用[^#]+(或*代替+if 字符可能不存在)来匹配所有字符直到下一个#.

preg_match('/1232#([^#]+)#/', $file, $match);

回答by ?mega

Use lookarounds:

使用环视:

preg_match("/(?<=#).*?(?=#)/", $file, $match)


Demo:

演示:

preg_match("/(?<=#).*?(?=#)/", "1232#hello world#", $match);
print_r($match)

Output:

输出:

Array
(
    [0] => hello world
)

Test it here.

在这里测试一下

回答by Jevon McPherson

What if you want the delimiter to also be included in the array, this would be more usefull for preg_split where you might not want each array element to begin and end with the delimiters, the example im about to show would would include the delimeters inside the array values. this would be what you would need preg_match('/\#(.*?)#/', $file, $match); print_r($match);this would output array( [0]=> #hello world# )

如果您希望分隔符也包含在数组中,这对于 preg_split 会更有用,因为您可能不希望每个数组元素以分隔符开头和结尾,我即将展示的示例将包含分隔符数组值。这将是你需要的,preg_match('/\#(.*?)#/', $file, $match); print_r($match);这将输出array( [0]=> #hello world# )

回答by Sean Redmond

It looks to me like you just have to get $match[1]:

在我看来,你只需要得到$match[1]

php > $file = "1232#hello world#";
php > preg_match("/1232\#(.*)\#/", $file, $match);
php > print_r($match);
Array
(
    [0] => 1232#hello world#
    [1] => hello world
)
php > print_r($match[1]);
hello world

Are you getting different results?

你得到不同的结果吗?

回答by Pankaj Khairnar

preg_match('/1232#(.*)#$/', $file, $match);