我遇到了这个问题,我确实找到了几个例子,但我似乎无法让它为我工作。
$string = '1. A post-hardcore band from Brazil 2. A rock band from Sweden';
我需要检索“1”之间的所有内容。和“2。”
在PHP中是否有某种简单的拆分功能,我可以这样使用?
$result = string_between_chars($string, "1. ", "2 .");
或者,如果我匹配数字
preg_match('~(1.|2.|3.|4.)~', ($string), $matches
无论如何,我可以将其修改为
的结果[0] => 1. A post-hardcore band from Brazil
[1] => 2. A rock band from Sweden
答案 0 :(得分:0)
我认为这可以解决问题:
<?php
function string_between_chars($string, $from, $to){
preg_match("/$from(.*)$to/",$string,$match);
return $match[1];
}
像这样使用:
$result = string_between_chars($string, '1\. ', '2\. ');
在点之前添加反斜杠。圆点在正则表达式中具有特殊含义。你可以用反斜杠来逃避它。
答案 1 :(得分:0)
以下正则表达式有效:
/\d+\..*?(?=\d+\.|$)/
在PHP中:
$str = '1. A post-hardcore band from Brazil 2. A rock band from Sweden'
.'3. A rock band from Hawaii 4. A metal band from Germany';
preg_match_all('/\d+\..*?(?=\d+\.|$)/',$str,$matches);
print_r($matches);
<强>输出:强>
Array
(
[0] => Array
(
[0] => 1. A post-hardcore band from Brazil
[1] => 2. A rock band from Sweden
[2] => 3. A rock band from Hawaii
[3] => 4. A metal band from Germany
)
)
答案 2 :(得分:0)