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
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
$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.
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);
How about using explode
:
$input = 'Posted On April 6th By Some Dude';
$result = explode(' By',$input);
return $result[0];
Advantages:
$result[1]
would return Some Dude
in this example)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.
One method would be:
$str = 'Posted On April 6th By Some Dude';
echo strtok($str, 'By'); // Posted On April 6th
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",",");
?>
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);
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?"
$var = "Posted On April 6th By Some Dude";
$new_var = substr($var, 0, strpos($var, " By"));
By using regular expression: $string = preg_replace('/\s+By.*$/', '', $string)
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!
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:
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
}
}
$variable = substr($initial, 0, strpos($initial, "By"));
if (!empty($variable)) { echo $variable; } else { echo $initial; }