Remove portion of a string after a certain character

0 votes
asked Apr 6, 2010 by belgin-fish

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

13 Answers

0 votes
answered Apr 6, 2010 by austin-fitzpatrick
$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.

0 votes
answered Apr 6, 2010 by outis

preg_replace offers one way:

$newText = preg_replace('/\bBy.*$/', '', $text);
0 votes
answered Apr 6, 2010 by tim-cooper
$var = "Posted On April 6th By Some Dude";
$new_var = substr($var, 0, strpos($var, " By"));
0 votes
answered Apr 6, 2010 by jyelton

You could do:

$posted = preg_replace('/ By.*/', '', $posted);
echo $posted;
0 votes
answered Apr 6, 2010 by jemfinch

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);
0 votes
answered Apr 6, 2010 by volkerk

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);
0 votes
answered Apr 6, 2010 by ming-tang

By using regular expression: $string = preg_replace('/\s+By.*$/', '', $string)

0 votes
answered Apr 15, 2013 by squarecandy

How about using explode:

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

Advantages:

0 votes
answered Apr 23, 2014 by salman-a

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 "
0 votes
answered Apr 2, 2015 by hadi

One method would be:

$str = 'Posted On April 6th By Some Dude';
echo strtok($str, 'By'); // Posted On April 6th
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...