douzhizao0270 2012-06-24 07:19
浏览 49
已采纳

PHP preg_match使用RegEx来匹配一个单词

I want to find all the demo words using PHP and regEx.

$input ='demo';
$pattern = ''; //$input can be used along with regex, please help here 
$text = 'This is dem*#o text, contains de12mo3 text, is .demo23* text' 

if(preg_match($pattern, $text))
{
 echo 'found';
}else{
 echo'not found';
}

the search word demo in the text may be present in the following format

1) may start with special characters/numbers Eg. "12*demo"
2) may contain special characters/numbers within the word Eg.  "de12*mo"
3) may end with special characters/numbers Eg. "demo12*"

please help I am stuck, thanks in advance!

Note: The $input can be max. of 15 in length

  • 写回答

3条回答 默认 最新

  • dongliantong3229 2012-06-24 07:27
    关注

    The Solution

    I would start by removing all special characters and numbers from the string, and then matching the word using word boundaries:

    $cleaned = preg_replace('/[^a-z ]+/i', '', 'This is dem*#o text, contains de12mo3 text, is .demo23* text');
    
    preg_match_all('/\bdemo\b/i', $cleaned, $matches, PREG_OFFSET_CAPTURE);
    
    var_dump($matches);
    

    Will give you (Codepad Demo):

    array(1) {
      [0] => array(3) {
        [0] => array(2) {
          [0] => string(4) "demo"
          [1] => int(8)
        }
    
        [1] => array(2) {
          [0] => string(4) "demo"
          [1] => int(27)
        }
    
        [2] => array(2) {
          [0] => string(4) "demo"
          [1] => int(40)
        }
      }
    }
    

    Explanation

    The first line replaces any characters in your string (called the subject argument) that match /[a-z ]+/i with '', essentially removing the characters. The regex matches any character (or group of characters) that is not (^) the letters a-z or a space. The i flag tells regex that the search should be case insensitive (This saves us from writing a-zA-Z).

    The next line uses word boundaries to match the word 'demo'. However, you could substitute in any word.

    New Regex Techniques

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效