PHP使用RegEx从字符串中捕获包含特殊字符的单词

PHP使用RegEx从字符串中捕获包含特殊字符的单词

问题描述:

I have special words in a string that i would like to capture based on the prefix.
Example Special words such as ^to_this should be caught.
I would need the word this because of the special prefix ^to_.
Here is my attempt but it is not working

preg_match('/\b(\w*^to_\w*)\b/', $str, $specialWordArr); 

but this returns an empty array

我希望根据前缀捕获字符串中的特殊单词。
示例 strong> 应该捕获^ to_this等特殊单词 code>。
由于特殊前缀 ^,我需要单词 this code> to _ code>。
这是我的尝试,但它无法正常工作 p>

  preg_match('/ \ b(\ w * ^ to_ \ w *)\  b /',$ str,$ specialWordArr);  
  code>  pre> 
 
 

但这会返回一个空数组 p> div>

Your code would be,

<?php
$mystring = 'Special words such as ^to_this should be caught';
$regex = '~[_^;]\w+[_^;](\w+)~';
if (preg_match($regex, $mystring, $m)) {
    $yourmatch = $m[1]; 
    echo $yourmatch;
    }
?>  //=> this

Explanation:

  • [_^;] Add the special characters into this character class to ensure that the begining of a word would be a special character.
  • \w+ After a special character, there must one or more word characters followed.
  • [_^;] Word characters must be followed by a special character.
  • (\w+) If these conditions are satisfied, capture the following one or more word characters into a group.

Without some additional examples this will work for what you've posted:

$str = 'Special words such as ^to_this should be caught';   

preg_match('/\s\^to_(\w+)\s/', $str, $specialWordArr);

echo $specialWordArr[1]; //this