Reputation: 31
I need to find a specic line of text, from several lines of text
So, I have a text file with several lines of text, eg:
JOHN
MIKE
BEN
*BJAMES
PETE
I read that contents into an array, with each line of text, placed into a seperate element of the array.
I then tested each element of the array, to find the line that starts with, say: *B
ie:
if ( preg_match( "/^\*(B)/",$contents[$a] ) )
why dosnt that work ?
Upvotes: 0
Views: 767
Reputation: 3414
Consider the following code:
$regex = "%\*B(.*?)%is";
if (preg_match($regex, $contents[a])) { /// do something }
Also you may find this slide very helpful for learning regular expressions:
http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/
Upvotes: 1
Reputation: 790
The following works for me (where $txt is your original data):
foreach ( explode("\n", $txt) as $a ) {
if ( preg_match( "/^\*B/", $a ) ) {
echo "**MATCH " . $a . "<br/>";
}
}
Upvotes: 0
Reputation: 70587
I wouldn't use double quotes here, because \ is an escape sequence:
if ( preg_match( '/^\*(B)/',$contents[$a] ) )
It works here for me though even with double quotes, so you might want to check what $contents[$a]
is:
$myline = "*BJAMES";
if( preg_match( "/^\*(B)/", $myline) )
{
echo "Yes\n";
}
Upvotes: 0