PHP preg_match在字符串之间插入 [英] PHP preg_match get in between string
本文介绍了PHP preg_match在字符串之间插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试获取字符串hello world
.
I'm trying to get the string hello world
.
这是我到目前为止所得到的:
This is what I've got so far:
$file = "1232#hello world#";
preg_match("#1232\#(.*)\##", $file, $match)
推荐答案
建议使用除#
之外的分隔符,因为您的字符串包含#
,并且使用非贪婪的(.*?)
来捕获字符#
.顺便说一下,如果#
也不是分隔符,则不需要在表达式中转义.
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 #
.
preg_match('/1232#([^#]+)#/', $file, $match);
这篇关于PHP preg_match在字符串之间插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文