Remove portion of a string after a certain character
PhpStringPhp Problem Overview
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
Php Solutions
Solution 1 - 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.
Solution 2 - Php
If you're using PHP 5.3+ take a look at the $before_needle flag of http://docs.php.net/function.strstr">strstr()</a>
$s = 'Posted On April 6th By Some Dude';
echo strstr($s, 'By', true);
Solution 3 - Php
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 returnSome Dude
in this example)
Solution 4 - Php
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.
Solution 5 - Php
One method would be:
$str = 'Posted On April 6th By Some Dude';
echo strtok($str, 'By'); // Posted On April 6th
Solution 6 - Php
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",",");
?>
Solution 7 - Php
Austin's answer works for your example case.
More generally, you would do well to look into the http://us.php.net/manual/en/ref.pcre.php">regular expression functions when the substring you're splitting on may differ between strings:
$variable = preg_replace('/By.*/', '', $variable);
Solution 8 - Php
$var = "Posted On April 6th By Some Dude";
$new_var = substr($var, 0, strpos($var, " By"));
Solution 9 - Php
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 "
Solution 10 - Php
preg_replace
offers one way:
$newText = preg_replace('/\bBy\b.*$/', '', $text);
The '\b' matches on a word boundary (it's zero-width and matches between word and non-word characters), ensuring it will only match a complete word. While the target word doesn't occur as part of any other words in the example, in general the target might appear as part of another word (e.g. "by" in "'Babylon Revisited', by F. Scott Fitzgerald" or "'Bloom County Babylon' by Berkely Breathed").
The '.*$' matches all text up to the end. '$' matches the end of the string and, while not strictly necessary for correctness, documents the intent of the regex (which are well known for becoming hard to read).
Regular expression matching starts at the start of the string, so this will replace starting at the first match. For how to instead match starting at the last, see "How to replace only the last match of a string with preg_replace?"
Solution 11 - Php
By using regular expression: $string = preg_replace('/\s+By.*$/', '', $string)
Solution 12 - Php
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!
Solution 13 - Php
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
}
}
Solution 14 - Php
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.
Solution 15 - Php
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 );
Solution 16 - Php
$variable = substr($initial, 0, strpos($initial, "By"));
if (!empty($variable)) { echo $variable; } else { echo $initial; }