CheeseFlavored CheeseFlavored - 19 days ago 9
PHP Question

PHP function for removing everything before a substring (with including option)

I need help making a php function. I want to create a function that removes everything before a specific word or character in a string. I know how to do that part, but I am new to making a function out of it, and I need to add an option to it... for example. If I have this string...

$str="I like to eat cheese, crackers and ham";


And I want to remove everything before the word cheese I could use this...

if(($pos=strpos($str,'cheese'))!== false) $str=substr($str,$pos);


and I'd end up with


cheese, crackers and ham


if I want to include the word cheese in the removal, I could use...

if(($pos=strpos($str,'cheese'))!== false) $str=substr($str,$pos+6);


the +6 at the end is the length of the word "cheese". I would get...


, crackers and ham


I'd like to be able to use a function called remove_before to get my new string, like this...

$str=remove_before("cheese",$str,0);


The 3rd variable would indicate if you also want to remove the word you're looking for. A zero here would mean, remove everything before the word cheese and a 1 would mean remove the word cheese AND everything before it.
Thank you.

Answer

What you're looking for is something like this:

<?php
function remove_before($needle, $haystack, $removeNeedle=false) {

    $pos = strpos($haystack, $needle);

    if (($pos !== false)) {
        return substr($haystack, $pos + (strlen($needle) * $removeNeedle));
    }

}

$needle = "cheese";
$haystack = "I like to eat cheese, crackers and ham";

echo remove_before($needle, $haystack, false);
?>

$pos + (strlen($needle)*$removeNeedle) $removeNeedle is a boolean, meaning its value is either 1 or 0. if you multiply by 1, then value is value, if you multiply by 0, value is 0. so basically, you multiply the length of needle by 1 or 0.

The boolean at the end, is optional, as its default value is false.

The code is written by me, and is free of use to anyone, without limit.