954,604 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Find any letter in string of numbers

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

$str = "0001564<strong>A</strong>58749655

I need to find thatA 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.

desup
Newbie Poster
24 posts since Jan 2012
Reputation Points: 10
Solved Threads: 5
 

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;
blocblue
Posting Pro in Training
475 posts since Jan 2008
Reputation Points: 142
Solved Threads: 79
 

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

desup
Newbie Poster
24 posts since Jan 2012
Reputation Points: 10
Solved Threads: 5
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: