PHP: substr() function The substr() function used to cut a part of a string from a string, starting at a specified position. The input string. Refers to the position of the string to start cutting. A positive number : Start at the specified position in the string.
The substr() and strpos() function is used to remove portion of string after certain character. strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string.
To get a substring between two characters:Get the index after the first occurrence of the character. Get the index of the last occurrence of the character. Use the String. slice() method to get a substring between the 2 characters.
To get the first character from a string, we can use the substr() function by passing 0,1 as second and third arguments in PHP.
If the strings are different (ie: [foo] & [/foo]), take a look at this post from Justin Cook. I copy his code below:
function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
$fullstring = 'this is my [tag]dog[/tag]';
$parsed = get_string_between($fullstring, '[tag]', '[/tag]');
echo $parsed; // (result = dog)
Regular expressions is the way to go:
$str = 'before-str-after';
if (preg_match('/before-(.*?)-after/', $str, $match) == 1) {
echo $match[1];
}
onlinePhp
function getBetween($string, $start = "", $end = ""){
if (strpos($string, $start)) { // required if $start not exist in $string
$startCharCount = strpos($string, $start) + strlen($start);
$firstSubStr = substr($string, $startCharCount, strlen($string));
$endCharCount = strpos($firstSubStr, $end);
if ($endCharCount == 0) {
$endCharCount = strlen($firstSubStr);
}
return substr($firstSubStr, 0, $endCharCount);
} else {
return '';
}
}
Sample use:
echo getBetween("abc","a","c"); // returns: 'b'
echo getBetween("hello","h","o"); // returns: 'ell'
echo getBetween("World","a","r"); // returns: ''
function getInnerSubstring($string,$delim){
// "foo a foo" becomes: array(""," a ","")
$string = explode($delim, $string, 3); // also, we only need 2 items at most
// we check whether the 2nd is set and return it, otherwise we return an empty string
return isset($string[1]) ? $string[1] : '';
}
Example of use:
var_dump(getInnerSubstring('foo Hello world foo','foo'));
// prints: string(13) " Hello world "
If you want to remove surrounding whitespace, use trim
. Example:
var_dump(trim(getInnerSubstring('foo Hello world foo','foo')));
// prints: string(11) "Hello world"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With