这就是我到现在所做的:
<?php
$patterns= '/staff_(?)/';
$replacements= '';
$string = 'staff_name as user_name';
$string2 = 'staff_phone as user_phone';
echo preg_replace($patterns, $replacements, $string)."<br>";
echo preg_replace($patterns, $replacements, $string2);
?>
输出预期为:
&#34; staff_name as user_name&#34;应该返回&#34; name&#34;
&#34; staff_phone as user_phone&#34;应该返回&#34;电话&#34;
答案 0 :(得分:5)
<?php
$str='staff_name as user_name';
echo $str = preg_replace("~staff_(.*?)_~","", $str); //"prints" name
$str='staff_name as user_phone';
echo $str = preg_replace("~staff_(.*?)_~","", $str); //"prints" phone
<?php
$str='staff_name as user_name';
$name_arr = explode('_',$str);
echo $name = array_pop($name_arr); //"prints" name
$str='staff_name as user_phone';
$phone_arr = explode('_',$str);
echo $phone = array_pop($phone_arr); //"prints" phone
答案 1 :(得分:0)
使用此.*_(\w+$)
这样做
<?php
$string = 'staff_name as user_name';
$string2 = 'staff_phone as user_phone';
echo preg_replace('/.*_(\w+$)/', '$1', $string)."\n";
echo preg_replace('/.*_(\w+$)/', '$1', $string2);