Page 1 of 1

Position in a string ?!?!?!

Posted: Tue Jan 25, 2005 11:02 am
by Calimero
I have done this n*n*n*n*n times in JavaScript and realy dont get how there is no function to work with it in php ?!?!

I have a string ex.

Code: Select all

$stringster = "first_word, second_word, third_word, forth_word, last_word";
I need php to check for "," commas ( I tried preg_match() and preg_match_all() ) but also (somehow) to show the index number in the string where the pattern is found.

Now this is not so hard with one-letter pattern, but how to do it with 2,3,4,5 long patterns ( I need the index number of the first character in the pattern found ).


There probably is simple solution - I looked at the almighty Doc. - and turned to other deities - You guys, and gals :D

Sample ( part's ) of code wellcome !


Thanks in ahead !

Posted: Tue Jan 25, 2005 11:12 am
by feyd
PREG_OFFSET_CAPTURE with preg_match_all

or

PREG_SPLIT_OFFSET_CAPTURE with preg_split

Posted: Tue Jan 25, 2005 12:04 pm
by rehfeld
you could also use strpos in a loop

Code: Select all

$offset = 0;
$commas = array();

while (false !== ($offset = strpos($haystack, ',', $offset))) {
    $commasї] = $offset;
}

Posted: Tue Jan 25, 2005 2:21 pm
by magicrobotmonkey
or, depending on what you are going to do with the output, you could explode() on yhour delimiter:

Code: Select all

$brokenOut = explode(",",$input);

...

Posted: Wed Jan 26, 2005 5:48 am
by Calimero
Just to thank you, I got it working, going to perfect it - and if something goes wrong :D


My Typewriter is up, overclocked and ready !

See ya !