[英]PHP capture word that contains special char from string using RegEx
我想根據前綴捕獲字符串中的特殊單詞。
示例 Special words such as ^to_this should be caught
。
由於特殊的前綴^to_
我需要this
詞。
這是我的嘗試,但是沒有用
preg_match('/\b(\w*^to_\w*)\b/', $str, $specialWordArr);
但這返回一個空數組
您的代碼是
<?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
說明:
[_^;]
將特殊字符添加到此字符類中,以確保單詞的開頭將是特殊字符。 \\w+
在特殊字符之后,必須跟隨一個或多個單詞字符。 [_^;]
單詞字符后必須帶有特殊字符。 (\\w+)
如果滿足這些條件,請將以下一個或多個單詞字符捕獲為一組。 如果沒有其他示例,這將適用於您發布的內容:
$str = 'Special words such as ^to_this should be caught';
preg_match('/\s\^to_(\w+)\s/', $str, $specialWordArr);
echo $specialWordArr[1]; //this
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.