【问题标题】:PHP regexping the string (extracting) [closed]PHP正则表达式字符串(提取)[关闭]
【发布时间】:2015-11-11 09:33:18
【问题描述】:

我需要从字符串中获取一个子字符串(参见示例,粗体部分)。所有字符串都以“input”开头,后跟 2 个下划线,中间有一些(1 到 7)个随机字符。谢谢!

例子:

input_7ax8_SOME_INFO

input_3f0max2_SOME_OTHER_INFO

input_k_ANOTHERINFO-any-chars-possible:0123456789

【问题讨论】:

  • 你提供的文字是HTML格式吗?

标签: php regex preg-replace


【解决方案1】:

使用“非下划线”+“下划线”乘以 2 的检测并获取之后的所有内容,您可以获得您要求的结果。

?: 用于不返回带下划线的部分的结果,因为需要 () 将它们组合在一起。

$input = 'input_k_ANOTHERINFO-any-chars-possible:0123456789';
preg_match( '~^(?:[^_]+_){2}(.*)$~', $input, $match );
var_export($match);

【讨论】:

    【解决方案2】:

    你只需要explode 和它的第三个参数:

    <?php
    $input = 'input_7ax8_SOME_INFO';
    $input = explode("_",$input,2); // Split 2 times
    $input[2] = '<b>'.$input[2].'</b>'; // Make the rest of the string bold
    $input = implode("_",$input); // re joining
    
    echo $input;
    ?>
    

    【讨论】:

    • 如果第三个参数包含下划线怎么办?
    • 请求是使用正则表达式,粗体部分只是为了标记如果我正确地解释问题所需要的内容。
    • 第三个参数只能包含整数值
    • @moorscode :只要它可以帮助 OP,为什么不呢?
    • @MichaelAntonio:我不这么认为,看:“ANOTHERINFO-any-chars-possible:0123456789”
    猜你喜欢
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    • 2011-12-05
    • 2014-07-06
    相关资源
    最近更新 更多