0

I am trying to grab text from a string that begins after the 3rd instance of a repeating variable

t|1t|2t|3t|4

I want to return the number 3 by finding the 3rd "t|"

I know how to get the string:

$pc1 = 'start';
$pc2 = 'end';


$pcb = strpos($string, $pc1,+2);
$pce = strpos($string, $pc2);


$data_point = substr($string,$pcb,$pce - $pcb);

But if I search for "t|" inside $data_point, it always leaves me with the first one and not the third

1
  • I revised the question to clarify that I am parsing a text string not html Commented Aug 28, 2021 at 23:59

3 Answers 3

1

You can explode the string into an array and get the number:

$arr = explode('t|', $string)
print_r($arr);

output:

Array
(
    [0] => 
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
)
Sign up to request clarification or add additional context in comments.

Comments

0

To find the last occurance you need to use strrpos

  $original = '7853412365412390';
  $search = '123';
  $position = strrpos($original, $search);

$position will be 11. With substr you get 5.

For more informations: https://www.php.net/manual/en/function.strrpos.php

Comments

0

You can also use explode, this give what is immediately after the end of the matched pattern.

    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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.