Jump to content

[SOLVED] simple matching problem.


Shaun

Recommended Posts

Could someone please have a look over the following code and help to as why it is not functioning correctly.

 

<?
$str = "some text here \"REC UNREAD\" some more text here";

if(preg_match('/REC READ/', '$str') == "TRUE"){
$status = "read";
} elseif(preg_match('/REC UNREAD/', '$str') == "TRUE"){
$status = "unread";
}

echo $status;
?>

 

for some reason it wont echo out the status correctly.

 

basically it pulls either REC READ or REC UNREAD from the string, and then echo's out whether it is read or un read.. I hope you can understand.

 

please help me as this is starting to bug me.

 

warm regards and thank you so much for the help.

Link to comment
https://forums.phpfreaks.com/topic/82714-solved-simple-matching-problem/
Share on other sites

To use your syntax

 

preg_match('/REC\sREAD/', $str) != 0

 

lose the quotes and add \s.  Preg_match only returns 'false' if there is an error, otherwise it returns the number of times there is a match.

 

if you wanted to get fancy, you could even do:

 

preg_match('/\"REC\s(\w+)\"/', $str, $status);

 

echo $status[1];

 

I think it's status[1], you might want to print_r($status) to get check the index though.

or

 

if(substr_count($str, 'REC READ') != 0){$status = "read";}

if(substr_count($str, 'REC UNREAD') != 0){$status = "unread";}

 

string functions are generally faster then preg functions, and should be used when you don't need the power or flexibility of a preg function

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.