Abhilash Cherukat
Abhilash Cherukat

Reputation: 65

How to preg_replace pattern on string

This is what I did till now:

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

Output expecting is :

"staff_name as user_name" should return "name"

"staff_phone as user_phone" should return "phone"

Upvotes: 2

Views: 1069

Answers (2)

The Regex way....

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

Non- Regex way using PHP native functions..

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

Upvotes: 5

Nambi
Nambi

Reputation: 12042

Use this .*_(\w+$)

Do like this

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

Upvotes: 0

Related Questions