Position in a string ?!?!?!

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Calimero
Forum Contributor
Posts: 310
Joined: Thu Jan 22, 2004 6:54 pm
Location: Milky Way

Position in a string ?!?!?!

Post 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 !
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

PREG_OFFSET_CAPTURE with preg_match_all

or

PREG_SPLIT_OFFSET_CAPTURE with preg_split
rehfeld
Forum Regular
Posts: 741
Joined: Mon Oct 18, 2004 8:14 pm

Post 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;
}
magicrobotmonkey
Forum Regular
Posts: 888
Joined: Sun Mar 21, 2004 1:09 pm
Location: Cambridge, MA

Post 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);
User avatar
Calimero
Forum Contributor
Posts: 310
Joined: Thu Jan 22, 2004 6:54 pm
Location: Milky Way

...

Post 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 !
Post Reply