0

I want to remove part of string from special world using php lang for example :

$string1 = "xABCb1/DEF/GHI/GKL";
$string2 = "yABCz/DEF/MNO/PQR";
$string3 = "zABC1112/DEF/STU/VWX";

I want to remove all words before from (DEF) and the result looks like this

$string1 = "DEF/GHI/GKL";
$string2 = "DEF/MNO/PQR";
$string3 = "DEF/STU/VWX";

The words before (DEF) are not static . it is changing. I just want the function to clear all the words that before (DEF)

KHALID
  • 87
  • 7
  • 1
    OK, great plan. So what have you tried, where is your code? You see, we are not a free coding service, we are here to help you to fix your own code... – arkascha Mar 11 '18 at 09:04

3 Answers3

1

There are many ways to do what you want here e.g string replace functions, regex and so on. But this is my way using strstr() because always try to use built in method instead of using regex at first.

$string1 = "xABCb1/DEF/GHI/GKL";
$string2 = "yABCz/DEF/MNO/PQR";
$string3 = "zABC1112/DEF/STU/VWX";
echo  strstr($string1, 'DEF')."\n"; 
echo  strstr($string2, 'DEF')."\n";
echo  strstr($string3, 'DEF');

Output:

DEF/GHI/GKL
DEF/MNO/PQR
DEF/STU/VWX

See Demo: https://eval.in/969773

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

Regular expressions offer a very powerful tool for such primitive string manipulations:

<?php
$input = [
    "xABCb1/DEF/GHI/GKL",
    "yABCz/DEF/MNO/PQR",
    "zABC1112/DEF/STU/VWX"
];
$anchor = "DEF";
$output = preg_replace('|^.*/(DEF/)|', '$1', $input);
print_r($output);

The output of above code obviously is:

Array
(
    [0] => DEF/GHI/GKL
    [1] => DEF/MNO/PQR
    [2] => DEF/STU/VWX
)
arkascha
  • 41,620
  • 7
  • 58
  • 90
0
    $string1 = "xABCb1/DEF/GHI/GKL";
    $string2 = "yABCz/DEF/MNO/PQR";
    $string3 = "zABC1112/DEF/STU/VWX";

    $string1 = ltrim($string1, 'xABCb1/');
    var_dump($string1); 

    $string2 = ltrim($string2, 'yABCz/');
    var_dump($string2);

    $string3 = ltrim($string3, 'zABC1112/');
    var_dump($string3); 

Output

 DEF/GHI/GKL
 DEF/MNO/PQR
 DEF/STU/VWX
Rashed
  • 2,349
  • 11
  • 26