I'm just wondering how I could remove everything after a certain substring in PHP
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"
$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.
preg_replace offers one way:
$newText = preg_replace('/\bBy.*$/', '', $text);
$var = "Posted On April 6th By Some Dude";
$new_var = substr($var, 0, strpos($var, " By"));
You could do:
$posted = preg_replace('/ By.*/', '', $posted);
Austin's answer works for your example case.
More generally, you would do well to look into the regular expression functions when the substring you're splitting on may differ between strings:
$variable = preg_replace('/By.*/', '', $variable);
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);
By using regular expression: $string = preg_replace('/\s+By.*$/', '', $string)
$string = preg_replace('/\s+By.*$/', '', $string)
How about using explode:
$input = 'Posted On April 6th By Some Dude';
$result = explode(' By',$input);
You can use list and explode functions:
list($result) = explode("By", "Posted On April 6th By Some Dude", 2);
// $result is "Posted On April 6th "
One method would be:
$str = 'Posted On April 6th By Some Dude';
echo strtok($str, 'By'); // Posted On April 6th