0

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 ?

3 Answers 3

1

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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";
}

Comments

0

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/>";
    }
}   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.