Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove portion of a string after a certain character

Tags:

string

php

$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.


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);

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)

You could do:

$posted = preg_replace('/ By.*/', '', $posted);
echo $posted;

This is a regular expression replacer function that finds the literal string ' By' and any number of characters after it (.*) and replaces them with an empty string (''), storing the result in the same variable ($posted) that was searched.

If [space]By is not found in the input string, the string remains unchanged.