Remove_before ()

Is there a better way to do below? (without the possibility of a fatal error)

function remove_before($needle,$haystack){ return substr(strstr($haystack,$needle),strlen($needle)); } 

like strstr ($ haystack, $ needle), but without a needle in the returned string, and I might also ask if this could be improved ...

 function remove_after($needle,$haystack){ return substr($haystack, 0, strrpos($haystack, $needle)); } 

note that delete the line after the strip after the last occurrence of the needle and delete before rinsing the line before the first occurrence of the needle.

edit Example:

 $needle = '@@'; $haystack = 'one@@two@@three'; remove_after($needle,$haystack);//returns one@@two remove_before($needle,$haystack)://returns two@@three 

edit I will leave it here so that other people can refer.

0
string php
source share
1 answer

Two functions are recorded in a function:

They have no error handling. For example, in remove_before: a needle not in a haystack forces it to pass false as the first argument to substr . I have not tried, but I am sure this will cause a runtime error.

In remove_before , strpos is faster and less memory than strstr .

Thus:

 function remove_before($needle, $haystack){ $pos = strpos($haystack, $needle); // No needle found if (false === $pos) return $haystack; return substr($haystack, $pos + strlen($needle)); } 

as well as remove_after :

 function remove_after($needle, $haystack){ $pos = strrpos($haystack, $needle); // No needle found if (false === $pos) return $haystack; return substr($haystack, 0, $pos); } 
+1
source share

All Articles