PHP正则表达式字符串(提取)


PHP regexping the string (extracting)

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

示例:

input_7ax8_SOME_INFO

input_3f0max2_SOME_OTHER_INFO

input_k_ANOTHERINFO任何可能的字符:0123456789

使用"非下划线"+"下划线"time2的检测,并获取之后的所有内容,您可以获得所需的结果。

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

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

您只需要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;
?>