PHP 对字符串进行正则表达式(提取)
PHP regexping the string (extracting)
我需要从字符串中获取一个子字符串(参见示例,粗体部分)。所有字符串都以 "input" 开头,后跟 2 个下划线,中间有一些(1 到 7)个随机字符。谢谢!
示例:
input_7ax8_SOME_INFO
input_3f0max2_SOME_OTHER_INFO
input_k_ANOTHERINFO-any-chars-possible:0123456789
你只需要 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;
?>
使用"non underscore" + "underscore" 2次的检测,把之后的所有内容都取出来就可以得到你要的结果。
?: 是为了不返回带下划线部分的结果,因为需要 () 将它们组合在一起。
$input = 'input_k_ANOTHERINFO-any-chars-possible:0123456789';
preg_match( '~^(?:[^_]+_){2}(.*)$~', $input, $match );
var_export($match);
我需要从字符串中获取一个子字符串(参见示例,粗体部分)。所有字符串都以 "input" 开头,后跟 2 个下划线,中间有一些(1 到 7)个随机字符。谢谢!
示例:
input_7ax8_SOME_INFO
input_3f0max2_SOME_OTHER_INFO
input_k_ANOTHERINFO-any-chars-possible:0123456789
你只需要 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;
?>
使用"non underscore" + "underscore" 2次的检测,把之后的所有内容都取出来就可以得到你要的结果。
?: 是为了不返回带下划线部分的结果,因为需要 () 将它们组合在一起。
$input = 'input_k_ANOTHERINFO-any-chars-possible:0123456789';
preg_match( '~^(?:[^_]+_){2}(.*)$~', $input, $match );
var_export($match);