如何在PHP中的字符串中获取所有美元唱歌及其后的文本

时间:2016-06-05 07:13:18

标签: php regex preg-match-all marc

marc 21标签可能包含一个带有几个美元符号的行,如:

$string='10$athis is text a$bthis is text b/$cthis is text$dthis is text d';

我试着匹配所有美元唱歌并在每次唱歌后得到文字,我的代码是:

preg_match_all("/\\$[a-z]{1}(.*?)/", $string, $match);

输出是:

Array
(
    [0] => Array
        (
            [0] => $a
            [1] => $b
            [2] => $c
            [3] => $d
        )

    [1] => Array
        (
            [0] => 
            [1] => 
            [2] => 
            [3] => 
        )

)

如何在每次唱歌后捕捉文字,以便输出:

Array
(
    [0] => Array
        (
            [0] => $a
            [1] => $b
            [2] => $c
            [3] => $d
        )

    [1] => Array
        (
            [0] => this is text a
            [1] => this is text b/
            [2] => this is text c
            [3] => this is text d
        )

)

2 个答案:

答案 0 :(得分:3)

您可以使用正向前瞻来匹配\$字面上或字符串结尾

(\$[a-z]{1})(.*?)(?=\$|$)

<强> Regex Demo

PHP代码

$re = "/(\\$[a-z]{1})(.*?)(?=\\$|$)/"; 
$str = "10\$athis is text a\$bthis is text b/\$cthis is text\$dthis is text d"; 
preg_match_all($re, $str, $matches);

<强> Ideone Demo

注意: - 您所需的结果位于Array[1]Array[2]Array[0]保留用于整个正则表达式找到的匹配。

答案 1 :(得分:2)

我认为一个简单的正则表达式就足够了

$re = '/(\$[a-z])([^\$]*)/'; 
$str = "10\$athis is text a\$bthis is text b/\$cthis is text\$dthis is text d"; 
preg_match_all($re, $str, $matches);
print_r($matches);

DEMO