Parsing 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
Zorth
Forum Commoner
Posts: 76
Joined: Fri Feb 20, 2004 8:00 pm

Parsing a String

Post by Zorth »

Does anyone know how I could parse out a string?

Let's say I had the string "The best player is Kanag and his level is 1."

Now let's say I get this string from a file and want to only print the name of the person, in this case it's Kanag. What all would I need to do to get the name alone? Seeing as PHP has no specific types, I haven't really seen a way to run through a string and change it or even compare them.

Any help is appreciated.

Zorth.
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

If the palyer name is always the 5th part of the string, like The best player is fred, The best player is john etc..then you could do..

$parts = explode(' ', $string);
$playername = $parts[4];
Zorth
Forum Commoner
Posts: 76
Joined: Fri Feb 20, 2004 8:00 pm

Post by Zorth »

That answeres scenerio one ;). What if it was like this:
~Kanag More info *Extra info

Basically in the file that is for the program to know what to expect, but is there a way to get rid of the '~' in PHP?
Illusionist
Forum Regular
Posts: 903
Joined: Mon Jan 12, 2004 9:32 pm

Post by Illusionist »

[php_man]str_replace[/php_man]

Code: Select all

$string = "~Kanag More info *Extra info";
$string = str_replace("~","",$string);
Zorth
Forum Commoner
Posts: 76
Joined: Fri Feb 20, 2004 8:00 pm

Post by Zorth »

Thanks ;).
User avatar
Heavy
Forum Contributor
Posts: 478
Joined: Sun Sep 22, 2002 7:36 am
Location: Viksjöfors, Hälsingland, Sweden
Contact:

Post by Heavy »

now that you have had some time to play with this, maybe it is time to try regular expressions?

http://www.php.net/manual/en/pcre.pattern.syntax.php

Then you get some real power at your fingertips.
Here's an example:
viewtopic.php?p=113982#113982
Post Reply