douxi8119 2016-06-23 12:12
浏览 24
已采纳

从文本中获取所有模式Word

If I have a text, how can I get all the strings with a certain pattern from the text? For example I want all the strings with this patters:

The word CER followed by any number followed by one of this characters ;, ,, . or space .

For exemple from the text bellow I wold like to have in an array the following results : CER123 , CER23 , CER01 , CER24

Lorem CER123 ipsum dolor sit amet, quod copiosae CER23,CER01;CER24 insolens et usu, vis CER34ERD ut saperet civibus accommodare.

I've tried this:

preg_match_all("/CER[0-9*]?/",$content,$m);

but it returns : CER1 , CER2 , CER0 , CER2 and CER3

  • 写回答

1条回答 默认 最新

  • dp0518 2016-06-23 12:16
    关注

    Use +, add a capturing group and create a character class for the characters you require after the value you need to get:

    preg_match_all('/(CER[0-9]+)[;,.\s]/',$content,$m);
                     ^        ^^^^^^^^^
    

    See the regex demo

    Pattern explanation:

    • (CER[0-9]+) - Group 1 capturing the parts of text you need:
      • CER - a sequence of literal characters CER (NOTE: If you need whole word CER only, after a non-word char or at the start of the string, add word boundaries: \bCER\b)
      • [0-9]+ (=\d+) - 1 or more digits
    • [;,.\s] - any char inside the character class: ;, ,, . or \s (whitespace - replace with a space if you only mean a regular space).

    PHP demo:

    $re= '/(CER[0-9]+)[;,.\s]/';
    $content = "Lorem CER123 ipsum dolor sit amet, quod copiosae CER23,CER01;CER24 insolens et usu, vis CER34ERD ut saperet civibus accommodare."; 
    preg_match_all($re, $content, $m);
    print_r($m[1]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法