[英]PHP preg_match get in between string
我正在尝试获取字符串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"
}
更好的方法是使用[^#]+
(如果可能不存在字符,则用*
代替+
)来匹配所有字符,直到下一个#
为止。
preg_match('/1232#([^#]+)#/', $file, $match);
使用环顾:
preg_match("/(?<=#).*?(?=#)/", $file, $match)
preg_match("/(?<=#).*?(?=#)/", "1232#hello world#", $match);
print_r($match)
Array
(
[0] => 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_split会更有用,因为您可能不希望每个数组元素都以分隔符开头和结尾,因此要显示的示例im会在分隔符内包含分隔符。数组值。 这就是你需要的preg_match('/\\#(.*?)#/', $file, $match); print_r($match);
preg_match('/\\#(.*?)#/', $file, $match); print_r($match);
这将输出array( [0]=> #hello world# )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.