[php] 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

This question is related to php string

The answer is


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

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 "

Use the strstr function.

<?php
$myString = "Posted On April 6th By Some Dude";
$result = strstr($myString, 'By', true);

echo $result ;

The third parameter true tells the function to return everything before first occurrence of the second parameter.


How about using explode:

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

Advantages:


$var = "Posted On April 6th By Some Dude";
$new_var = substr($var, 0, strpos($var, " By"));

Try this.

function strip_after_string($str,$char)
    {
        $pos=strpos($str,$char);    
        if ($pos!==false) 
        {
            //$char was found, so return everything up to it.
            return substr($str,0,$pos);
        } 
        else 
        {
            //this will return the original string if $char is not found.  if you wish to return a blank string when not found, just change $str to ''
            return $str; 
        }
    }

Usage:

<?php
    //returns Apples
    $clean_string= strip_after_string ("Apples, Oranges, Banannas",",");
?>

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

if (!empty($variable)) { echo $variable; } else { echo $initial; }

Hey I thought this may be useful for someone who wants to replace the characters comes after the "By", for example in the text he given has by at the 20th position of his string so if you want to ignore the by you should add + 2 to the position then which will ignore the 20th position and it will replace all after coming the by it will work if you give the exact character length of the text you're gonna replace.

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

Why...

This is likely overkill for most people's needs, but, it addresses a number of things that each individual answer above does not. Of the items it addresses, three of them were needed for my needs. With tight bracketing and dropping the comments, this could still remain readable at only 13 lines of code.

This addresses the following:

  • Performance impact of using REGEX vs strrpos/strstr/strripos/stristr.
  • Using strripos/strrpos when character/string not found in string.
  • Removing from left or right side of string (first or last occurrence) .
  • CaSe Sensitivity.
  • Wanting the ability to return back the original string unaltered if search char/string not found.

Usage:

Send original string, search char/string, "R"/"L" for start on right or left side, true/false for case sensitivity. For example, search for "here" case insensitive, in string, start right side.

echo TruncStringAfterString("Now Here Are Some Words Here Now","here","R",false);

Output would be "Now Here Are Some Words ". Changing the "R" to an "L" would output: "Now ".

Here's the function:

function TruncStringAfterString($origString,$truncChar,$startSide,$caseSensitive)
{
    if ($caseSensitive==true && strstr($origString,$truncChar)!==false)
    {
        // IF START RIGHT SIDE:
        if (strtoupper($startSide)=="R" || $startSide==false)
        {   // Found, strip off all chars from truncChar to end
            return substr($origString,0,strrpos($origString,$truncChar));
        }

        // IF START LEFT SIDE: 
        elseif (strtoupper($startSide)=="L" || $startSide="" || $startSide==true)
        {   // Found, strip off all chars from truncChar to end
            return strstr($origString,$truncChar,true);
        }           
    }
    elseif ($caseSensitive==false && stristr($origString,$truncChar)!==false)
    {           
        // IF START RIGHT SIDE: 
        if (strtoupper($startSide)=="R" || $startSide==false)
        {   // Found, strip off all chars from truncChar to end
            return substr($origString,0,strripos($origString,$truncChar));
        }

        // IF START LEFT SIDE: 
        elseif (strtoupper($startSide)=="L" || $startSide="" || $startSide==true)
        {   // Found, strip off all chars from truncChar to end
            return stristr($origString,$truncChar,true);
        }
    }       
    else
    {   // NOT found - return origString untouched
        return $origString;     // Nothing to do here
    }           

}

You could do:

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

Below is the most efficient method (by run-time) to cut off everything after the first By in a string. If By does not exist, the full string is returned. The result is in $sResult.

$sInputString = "Posted On April 6th By Some Dude";
$sControl = "By";

//Get Position Of 'By'
$iPosition = strpos($sInputString, " ".$sControl);
if ($iPosition !== false)
  //Cut Off If String Exists
  $sResult = substr($sInputString, 0, $iPosition);
else
  //Deal With String Not Found
  $sResult = $sInputString;

//$sResult = "Posted On April 6th"

If you don't want to be case sensitive, use stripos instead of strpos. If you think By might exist more than once and want to cut everything after the last occurrence, use strrpos.

Below is a less efficient method but it takes up less code space. This method is also more flexible and allows you to do any regular expression.

$sInputString = "Posted On April 6th By Some Dude";
$pControl = "By";

$sResult = preg_replace("' ".$pControl.".*'s", '', $sInputString);

//$sResult = "Posted On April 6th"

For example, if you wanted to remove everything after the day:

$sInputString = "Posted On April 6th By Some Dude";
$pControl = "[0-9]{1,2}[a-z]{2}"; //1 or 2 numbers followed by 2 lowercase letters.

$sResult = preg_replace("' ".$pControl.".*'s", '', $sInputString);

//$sResult = "Posted On April"

For case insensitive, add the i modifier like this:

$sResult = preg_replace("' ".$pControl.".*'si", '', $sInputString);

To get everything past the last By if you think there might be more than one, add an extra .* at the beginning like this:

$sResult = preg_replace("'.* ".$pControl.".*'si", '', $sInputString);

But here is also a really powerful way you can use preg_match to do what you may be trying to do:

$sInputString = "Posted On April 6th By Some Dude";

$pPattern = "'Posted On (.*?) By (.*?)'s";
if (preg_match($pPattern, $sInputString, $aMatch)) {
  //Deal With Match
  //$aMatch[1] = "April 6th"
  //$aMatch[2] = "Some Dude"
} else {
  //No Match Found
}

Regular expressions might seem confusing at first but they can be really powerful and your best friend once you master them! Good luck!


One method would be:

$str = 'Posted On April 6th By Some Dude';
echo strtok($str, 'By'); // Posted On April 6th

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


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

preg_replace offers one way:

$newText = preg_replace('/\bBy.*$/', '', $text);