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]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)