Hi all, I need help with one script.
If i Have string like

$str = "0001564[B]A[/B]58749655

I need to find that A in this string, and count which number is it (When tha A is on the third place, return 2 [starting from 0])
A think regular expression will be the best fo it, but i don't know how to put it together.
Please help me!
Thank your really much.

Edited by desup: n/a

5 Years
Discussion Span
Last Post by desup

I think your problem needs to be split into two parts. First, finding the letter(s). Second, finding the position.

$string = '0001564AC587B4965B5';
$positions = array();

// Find all letters
preg_match_all('/[a-z]/i', $string, $matches);

// Check if any letters found
if(isset($matches[0])) {
    $offset = 0;

    // Iterate through each letter and find corresponding position
    foreach($matches[0] as $letter) {
        $position = strpos($string, $letter, $offset);

        if($position <> false) {
            $positions[] = "{$letter}: {$position}";
            $offset = $position + 1;

echo '<pre>'; print_r($positions); echo '</pre>'; die;

Edited by blocblue: Added support for duplicate letters


Yeah, that what I was looking for .. thanks man!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.