2

一个 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
        )

)
4

2 回答 2

3

您可以使用积极的前瞻来匹配\$字面或字符串的结尾,例如

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

正则表达式演示

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 演示

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

于 2016-06-05T07:17:33.193 回答
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);

演示

于 2016-06-05T07:49:22.300 回答