Remove portion of a string after a certain character

I'm just wondering how I could remove everything after a certain substring in PHP

ex:

Posted On April 6th By Some Dude

I'd like to have it so that it removes all the text including, and after, the sub string "By"

Thanks


Solution 1:

$variable = substr($variable, 0, strpos($variable, "By"));

In plain english: Give me the part of the string starting at the beginning and ending at the position where you first encounter the deliminator.

Solution 2:

If you're using PHP 5.3+ take a look at the $before_needle flag of strstr()

$s = 'Posted On April 6th By Some Dude';
echo strstr($s, 'By', true);

Solution 3:

How about using explode:

$input = 'Posted On April 6th By Some Dude';
$result = explode(' By',$input);
return $result[0];

Advantages:

  • Very readable / comprehensible
  • Returns the full string if the divider string (" By" in this example) is not present. (Won't return FALSE like some of the other answers.)
  • Doesn't require any regex.
    • "Regular expressions are like a particularly spicy hot sauce – to be used in moderation and with restraint only when appropriate."
    • Regex is slower than explode (I assume preg_split is similar in speed to the other regex options suggested in other answers)
  • Makes the second part of the string available too if you need it ($result[1] would return Some Dude in this example)