我试图从重复变量
的第三个实例之后开始的字符串中抓取文本t|1t|2t|3t|4
我想通过找到第3个"t|">
返回数字3我知道如何得到字符串:
$pc1 = 'start';
$pc2 = 'end';
$pcb = strpos($string, $pc1,+2);
$pce = strpos($string, $pc2);
$data_point = substr($string,$pcb,$pce - $pcb);
但是如果我搜索"t|"在$data_point中,它总是留给我第一个而不是第三个
您可以将字符串explode
到数组中并得到数字:
$arr = explode('t|', $string)
print_r($arr);
输出:
Array
(
[0] =>
[1] => 1
[2] => 2
[3] => 3
[4] => 4
)
要查找最后出现的字符,需要使用strpos
$original = '7853412365412390';
$search = '123';
$position = strrpos($original, $search);
$position将为11。使用substr可以得到5.
更多信息:https://www.php.net/manual/en/function.strrpos.php
你也可以使用explosion,这将给出匹配模式结束后的内容。
function pattern_match($i = 0, $txt = "", $pattern = "")
{
$j = 0;
while($j <= strlen($txt)) {
if ($j >= strlen($pattern)) return true;
if ($pattern[$j] != $txt[$i + $j]) return false;
$j++;
}
}
function scan($txt = "", $pattern = "")
{
$i = 0; $matches = [];
while ($i <= strlen($txt)) {
if(pattern_match($i, $txt, $pattern)) $matches[] = $i + strlen($pattern) - 1;
$i++;
}
return $matches;
}
function get_nth($n = 0, $txt = "", $pattern = "", $j = 1)
{
$indicies = scan($txt, $pattern);
return $indicies[$n] ? substr($txt, $indicies[$n] + 1, $j) : null;
}
$txt = "t|1t|2t|3t|xyz012";
$pattern = "t|";
var_dump(
get_nth(0, $txt, $pattern),
get_nth(1, $txt, $pattern),
get_nth(2, $txt, $pattern),
get_nth(3, $txt, $pattern, 3) // any char to the right
)
// string(1) "1" string(1) "2" string(1) "3" string(3) "xyz"