简体   繁体   English

PHP preg_match在字符串之间插入

[英]PHP preg_match get in between string

I'm trying to get the string hello world . 我正在尝试获取字符串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);

Use lookarounds: 使用环顾:

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

Demo: 演示:

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

Output: 输出:

Array
(
    [0] => hello world
)

Test it here . 在这里测试。

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? 您得到不同的结果吗?

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

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. 如果您希望分隔符也包含在数组中,该方法对于preg_split会更有用,因为您可能不希望每个数组元素都以分隔符开头和结尾,因此要显示的示例im会在分隔符内包含分隔符。数组值。 this would be what you would need preg_match('/\\#(.*?)#/', $file, $match); print_r($match); 这就是你需要的preg_match('/\\#(.*?)#/', $file, $match); print_r($match); preg_match('/\\#(.*?)#/', $file, $match); print_r($match); this would output array( [0]=> #hello world# ) 这将输出array( [0]=> #hello world# )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM