【问题标题】:Extract substrings before or after underscore在下划线之前或之后提取子字符串
【发布时间】:2017-05-05 04:43:48
【问题描述】:

我尝试使用preg_match_all() 函数来搜索_ 之后的字符串。我想要的输出是reset,text,email。我尝试使用regexr 编辑器制作它,并且能够使用[_]+[a-z]* 制作它,但这将包括_reset, _text, _text。字符串将是:

$str = 'button_reset,location_text,email_text';

预期输出:

reset
text
email

【问题讨论】:

  • 您的预期输出没有意义。 “电子邮件”不在下划线之后。

标签: php regex string substring preg-match-all


【解决方案1】:

正则表达式: /\_\K[a-zA-Z0-9]+

1. \_\K 这将匹配 _ 并且 \K 将重置整个匹配。

2. [a-zA-Z0-9]+ 将匹配所有这些字符

Try this code snippet here

<?php

ini_set('display_errors', 1);
$str = 'button_reset,location_text,email_text';
preg_match_all("/\_\K[a-zA-Z0-9]+/",$str,$matches);
print_r($matches);

输出:

Array
(
    [0] => Array
        (
            [0] => reset
            [1] => text
            [2] => text
        )
)

【讨论】:

    【解决方案2】:

    这个任务最好避免使用正则表达式,只使用str_replace()

    输入:

    $str = 'button_reset,location_text,email_text';
    

    输出为数组的代码:

    var_export(explode(',',str_replace(['button_reset','location_text','email_text'],['reset','text','email'],$str)));
    // array (
    //    0 => 'reset',
    //    1 => 'text',
    //    2 => 'email',
    // )
    

    或者,如果您坚持,Regex (Demo Link):

    /button_\K[^,]+|,location_\K[^,]+|,\K[^_]+(?=_text)/
    

    正则表达式分解:

    button_\K[^,]+     #Match one or more non-comma-characters after button_
    |                  #or
    ,location_\K[^,]+  #Match one or more non-comma-characters after location_
    |                  #or
    ,\K[^_]+(?=_text)  #Match one or more non-underscore-characters that are
                       # immediately followed by _textafter button_
    

    每个条件表达式中的\K 表示从这一点开始匹配,有效地消除了在这种情况下使用捕获组的需要。 当使用捕获组时,preg_match_all() 创建了多个子数组——一个填充了全字符串匹配,至少一个填充了捕获的值。 应尽可能使用\K,因为它可以将数组大小减少多达 50%。

    代码:

    $array=preg_match_all('/button_\K[^,]+|,location_\K[^,]+|,\K[^_]+(?=_text)/',$str,$out)?$out[0]:[];
    var_export($array);
    

    同样的输出:

    array ( 0 => 'reset', 1 => 'text', 2 => 'email', )
    

    【讨论】:

    • 我想使用 preg_match()
    • 这次不是明智的选择。我可以制作一个,但这不是这项任务的正确功能。给我一分钟。
    猜你喜欢
    • 2014-03-23
    • 2011-03-06
    • 2012-01-29
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多