简体   繁体   English

使用PHP preg_match

[英]using PHP preg_match

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 然后,我测试了数组的每个元素,以找到以* B开头的行。

ie: 即:

if ( preg_match( "/^\*(B)/",$contents[$a] ) )

why dosnt that work ? 为什么不起作用?

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/ http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/

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: 即使使用双引号,它也对我有用,因此您可能要检查$contents[$a]是什么:

$myline = "*BJAMES";
if( preg_match( "/^\*(B)/", $myline) )
{
  echo "Yes\n";
}

The following works for me (where $txt is your original data): 以下对我有用(其中$ txt是您的原始数据):

foreach ( explode("\n", $txt) as $a ) {
    if ( preg_match( "/^\*B/", $a ) ) {
        echo "**MATCH " . $a . "<br/>";
    }
}   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM