php - 如何在 PHP 中获取字符串中的所有美元符号及其后面的文本

标签 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
        )

)

最佳答案

您可以使用正向前瞻来匹配 \$ 字面意思或字符串结尾,例如

(\$[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] 保留用于整个正则表达式找到的匹配。

关于php - 如何在 PHP 中获取字符串中的所有美元符号及其后面的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37639392/

相关文章:

regex - 在分隔符内替换 (N++)

PHP:preg_match_all首先匹配内括号?

php - 更好的 strip 化方法 php 正则表达式

php - 每年更新一次记录,全年平均分布

javascript - 如何将数据网格导出到excel?

php - 使用 PHP 正则表达式从 html 中提取 JSON 对象

java - 无法映射正则表达式 - java.lang.IllegalArgumentException : The number of capturing groups in the pattern segment

PHP 与 MYSQL DB 基于角色的登录重定向

PHP & MySQL : mysqli_num_rows() expects parameter 1 to be mysqli_result, bool 值

php - 计算字符串中图像的长度