PHP preg_match进入字符串之间

PHP preg_match进入字符串之间,php,regex,preg-match,Php,Regex,Preg Match,我正在尝试获取字符串hello world 到目前为止,我得到的是: $file = "1232#hello world#"; preg_match("#1232\#(.*)\##", $file, $match) 建议使用除之外的分隔符,因为字符串包含,并使用非贪婪的(.*)捕获之前的字符。顺便提一下,#如果不是分隔符,则不需要在表达式中转义 $file = "1232#hello world#"; preg_match('/1232#(.*?)#/', $file, $match);

我正在尝试获取字符串
hello world

到目前为止,我得到的是:

$file = "1232#hello world#";

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

建议使用除
之外的分隔符,因为字符串包含
,并使用非贪婪的
(.*)
捕获
之前的字符。顺便提一下,
#
如果不是分隔符,则不需要在表达式中转义

$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"
}
更好的方法是使用
[^#]+
(或者
*
而不是
+
,如果字符可能不存在)将所有字符匹配到下一个


在我看来,您只需获得
$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
您是否得到了不同的结果?

使用环顾四周:

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

测试它

如果您希望分隔符也包含在数组中,这对preg\u split更有用,因为您可能不希望每个数组元素以分隔符开头和结尾,im将要显示的示例将包括数组值中的delimeters。这将是您需要的
preg\u match('/\\\\\\\(.*)/',$file,$match);打印(匹配)这将输出
数组(
[0]=>#你好,世界#

)

太快了,谢谢!你能给出更多你想匹配的字符串的例子吗?很抱歉,有双反斜杠。我想我需要再加一个反斜杠使其可见。
preg_match(“/”?你能解释一下它是如何工作的吗?没关系,但我不明白(?@KrzysztofJarosz-
)?
preg_match("/(?<=#).*?(?=#)/", $file, $match)
preg_match("/(?<=#).*?(?=#)/", "1232#hello world#", $match);
print_r($match)
Array
(
    [0] => hello world
)