简体   繁体   中英

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?

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

你需要缓冲读取php文件并添加条件,如果在文件中找到字符串变量,然后根据需要操作它我不认为是任何其他方式

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM