Search code examples
phphtmlmysqlifindstrpos

Find entry between two entries in a php variable


I have a php variable that looks like this q1q32q1qq2q14q2qq3q16q3q. The logic of this variable is that an entry starts with for instance q1q and ends with q1q and in between those two entries there is a number, in this example 32. What I want is to write a code that finds the number in between given that you know q1q. This is what I started to write

strpos($participants, "q" . $_SESSION["UserID"] . "q")

In accordance with the above example $_SESSION["UserID"] is equal to 1 and $participants is the variable containing q1q32q1qq2q14q2qq3q16q3q. Any ideas on how to complete my code?


Solution

  • try preg_match

    $str = 'q1q32q1qq2q14q2qq3q16q3q';
    $word1 = 'q1q';
    $word2 = 'q1q';
    preg_match('/'.preg_quote($word1).'(.*?)'.preg_quote($word2).'/is', $str, $match);
    
    print_r($match); //$match[1] will have desired output
    

    output:

    Array
    (
        [0] => q1q32q1q
        [1] => 32
    )
    

    you can try with strpos and substr but it quite lengthy see below example:

    echo substr($str, (strpos($str, $word1) + strlen($word1)), (strpos($str, $word2, 1) - strlen($word2))); //output: 32