Jump to content

Find a word in a string?


br3nn4n

Recommended Posts

I know this is close to one of the most over-asked questions out there but here goes:

 

I have a text file. It has lines like so:

 

Background Color|backgroundcolor|#3356CC

 

Each one is a setting. First is the friendly name, second part is the technical name, and third part is the value for the setting. Hope that makes sense. They're separated by the "|" character.

 

I need to find the line in which a phrase exists. Say, I want to find the line with the site's title:

 

Website Title|sitetitle|John's Hardware

 

So the third element of that line. But how can I run through and do that? I've tried in_array, strpos...in various forms and if sequences. But I fail in this case...haha..

 

Thanks in advance for any help!

Link to comment
https://forums.phpfreaks.com/topic/156755-find-a-word-in-a-string/
Share on other sites

preg_match never fails me for finding stuff in strings. I'd loop through the file and test each line using that. so if you need to find 'sitetitle' then preg_match('/sitetitle/',$lineFromFile) will return something that evaluates to true when $lineFromFile has 'sitetitle' in it somewhere. that should find it just fine. if you open your text file into an array with file() then you can loop through the file very easily. you can also use explode() to break the line up like this:

 

list($friendly,$name,$value) = explode("|",$lineFromFile);

 

 

although I agree with using explode, I wouldn't use preg_match.

 

for straight text matches use strpos and !== instead of != as it might otherwise evualate things wrong when it's found on the very first position. (0 and false are equal to eachother using != )

if( strpos( $haystack, $needle  ) !== false )

I forgot to give a reason as to why didn't I?

Quoting the preg_match page on php.net

Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster.

 

if you're simply after the text after the last | in the string:

echo strrchr( "Website Title|sitetitle|John's Hardware","|" );

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.