• support@answerspoint.com

Get a substring between two strings in PHP


Extract a substring between two characters in a string PHP

So you need to get a subtring between two strings?  I wanted to solve the problem once-and-for-all in a more general-purpose way.
Using PHP to Get a String Between Two Strings.

My string is: "reply-234-private", i want to get the number after "reply-" and before "-private", it is "234". I have tried with following code but it returns an empty result:

I need a function that returns the substring between two words (or two characters). I'm wondering whether there is a php function that achieves that. I do not want to think about regex (well, I could do one but really don't think it's the best way to do that). Thinking of strpos and substr functions. Here's an example:
$string = "foo I wanna a cake foo";



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)
  • answered 8 years ago
  • B Butts

function GetBetween($var1="",$var2="",$pool){
$temp1 = strpos($pool,$var1)+strlen($var1);
$result = substr($pool,$temp1,strlen($pool));
if($dd == 0){
$dd = strlen($result);

return substr($result,0,$dd);

Sample use:

echo GetBetween("a","c","abc"); // returns: b

echo GetBetween("h","o","hello"); // returns: ell
  • answered 8 years ago
  • Sunny Solu

Your Answer

    Facebook Share        
  • asked 8 years ago
  • viewed 4691 times
  • active 8 years ago

Best Rated Questions