sf_admin819 sf_admin819 - 1 year ago 100
PHP Question

How to remove substring up to a certain character?

We have a string that is constantly generating the following pattern below. Ideally we would like to get rid of the string (all characters) up to the first "/" found. I have tried the following but it is not working. Need assistance to see what i am missing.

The goal is to remove all characters before the first "/" and the "/" itself from the beginning. The tricky part is that the string before the first "/" can vary in length.

Example strings:

  1. test-item/test-test1/test-2/test

  2. test-item2/test

  3. abdc/test/test/test

Example code that i tried (where $str is example strings above):

$patt = '/.+\/';
$repl = '';
$str = preg_replace($patt, $repl, $str);

Current output:

  1. test

  2. test

  3. test

Desired string output:

  1. test-test1/test-2/test

  2. test

  3. test/test/test

Answer Source

Here's a method using the substr() and strpos() functions that will work:

 $str = substr($str, strpos($str, '/') + 1 );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download