如何在字符串上preg_replace模式

时间:2014-03-21 07:10:56

标签: php regex preg-replace

这就是我到现在所做的:

<?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;

2 个答案:

答案 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

Demo

enter image description here

使用PHP本机函数的非正则表达方式..

<?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

Demo

答案 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);

Demo