views:

224

answers:

7

Hi, 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

+7  A: 
$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.

Austin Fitzpatrick
+1  A: 

You could do:

$posted = preg_replace('/ By.*/', '', $posted);
echo $posted;
JYelton
Regex seems like overkill here...
thetaiko
+1, clean and sweet
stereofrog
A: 

preg_replace offers one way:

$newText = preg_replace('/\bBy.*$/', '', $text);
outis
+1  A: 
$var = "Posted On April 6th By Some Dude";
$new_var = substr($var, 0, strpos($var, " By");
Tim Cooper
+1  A: 

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);
jemfinch
+1, This is right. If you wanted to also split on "Author:" or "Written By:" Or "Used with the consent of:" it would probably be easiest to make a regular expression. When I don't do any regex logic, though, I tend to avoid them as they seem to immediately add a level of complexity to the code (at least to me)
Austin Fitzpatrick
+1  A: 

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);
VolkerK
A: 

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

SHiNKiROU