tags:

views:

30

answers:

2

How would you return part of a string based on the contents of the string in php. Unlike substr() and related functions where you use an integer length

So if we are given a string like this here is a nice string that is being used as an example

How could we return a string like this

nice string

Somehow we have to pass the function a and that so it knows the start and end point. It will find the first a and then start keeping track of characters then when it finds that it will stop, and return.

To be clear: we know the contents of the original string... and the arguments sent.

+2  A: 

Use this function:

function get_string_between($string, $start, $end)
{
    $ini = strpos($string,$start);
    if ($ini == 0)
        return "";
    $ini += strlen($start);
    $len = strpos($string,$end,$ini) - $ini;
    return substr($string,$ini,$len);
}

$input = 'here is a nice string that is being used as an example';
$output = get_string_between($input, 'a', 'that');
echo $output;  //outputs: nice string
shamittomar
This prints ' nice string ', but is it what it should be? The return string should be 'nice string' - without the whitespace.
vtorhonen
@vtorhonen, For that, you can use `get_string_between($input, 'a ', 'that');`
shamittomar
+2  A: 

You could use regular expressions too with preg_match:

<?php

function get_string_between($string,$start,$end) {
    preg_match("/\b$start\b\s(.*?)\s\b$end\b/",$string,$matches);
    return $matches[1];
}

$str = "here is a nice string that is being used as an example";
print get_string_between($str,"a","that")."\n";

?>
vtorhonen