Select part of a string

PythonPython Forum LeaderThe Royal RAM
Lets pretend I have the variable $string which contains "You are currently reading text".

How would I select everything BETWEEN the word "are" and "reading" and put that into a variable?

Thanks

The Royal Ram

Comments

  • ChroderChroder Senior Member The Royal RAM
    PHP has a collection of string functions that when combined can let you do just about anything.

    Depending on how you want to go about things, there are usually more then one way to achieve the result you wish.

    For example, you could simply use some regex to replace everything else with nothing:

    [php]$str = "You are currently reading text";

    $new_str = preg_replace('#^(.*?)(are)(.*?)(reading)(.*?)$#', '$3', $str);

    echo $new_str; // ' currently ';[/php]

    Or get the locations of 'are' and 'reading' and then use substr:
    [php]$str = "You are currently reading text";

    echo strBetween($str, 'are', 'reading');

    function strBetween($string, $str1, $str2)
    {
    $pos1 = strpos($string, $str1);
    $len1 = strlen($str1);
    $pos2 = strpos($string, $str2);
    $len2 = strlen($str2);

    if($pos1 === false || $pos2 === false)
    return false;

    return substr($string, ($pos1 + $len1), ($pos2 - $pos1 - $len1));
    }[/php]

    Etc.
  • PythonPython Forum Leader The Royal RAM
    Ahh I see..

    Thanks :D

    The Royal Ram

Sign In or Register to comment.