PHP – substring between two strings

In this post we will show you how to get substring between two strings in PHP.
we will show you different method for parse a string between two strings and How to extract content between two delimiters using PHP.

Method – 1

By usin get_between_data function, we can find substring between start and end.
in this function you have to pass start and end data and it will give you substring result.

function get_between_data($string, $start, $end)
{
$pos_string = stripos($string, $start);
$substr_data = substr($string, $pos_string);
$string_two = substr($substr_data, strlen($start));
$second_pos = stripos($string_two, $end);
$string_three = substr($string_two, 0, $second_pos);
// remove whitespaces from result
$result_unit = trim($string_three);
// return result_unit
return $result_unit;
}

$input_str = "test string start data end test string.";
$unit = get_between_data($input_str, 'start', 'end');

echo $unit; // Outputs: "data"

Method – 2

By usin explode method we conver string in to array by “test” separator. so it will convert in to array and you abel to get thet data.

$input_str = "Xdata test HD01 test 1data";

$result_array = explode('test',$input_str);

print_r($result_array);

echo $result_array[1];

Method – 3

By usin this preg_replace and regex can get data between string. In this method we pass start and end data to get substring.

$input_str = "Xdata test HD01 test 1data";
$between = preg_replace('/(.*)test(.*)test(.*)/sm', '\2', $input_str);
echo $between;

Method – 4

By usin get_between_data function, we can find substring between start and end.
in this function you have to pass start and end data and it will give you substring result.

function get_between_data($input_str,$start,$end){
$result_array = explode($start, $input_str);
if (isset($result_array[1])){
$result_array = explode($end, $result_array[1]);
return $result_array[0];
}
// result null
return '';
}

$input_str = "Find data substring between two strings !!";
$start  = "Find data ";
$end    = " two strings !!";
$output_result = get_between_data($input_str,$start,$end);
echo $output_result;

Method – 5

By usin this preg_replace and regex can get data between string. In this method we pass start and end data to get substring.

$input_str = "[userid=256][userid=345]";
preg_match_all("/\[userid=([0-9]+)\]/", $input_str, $matches_res);

$modids_array = $matches_res[1];

foreach( $modids_array as $userid )
{
echo $userid."\n";
}

Leave a Comment

Your email address will not be published. Required fields are marked *

  +  32  =  36

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US