[英]PHP regular expression to match words
給定一個字符串,我想要一個包含單詞的字符串數組,每個字符串前面都有任何非單詞字符。
示例輸入字符串:
one "two" (three) -four-
字符串中的單詞可以是任何內容,甚至是亂碼,帶有任意數量的標點符號或符號。
我想看到的:
array: one "two " (three ) -four -
本質上,對於每場比賽,最后一件事是一個單詞,前面是前一場比賽剩下的任何東西。
我將在 PHP 中使用它。 我嘗試了 preg_match_all() 和 preg_split() 的各種組合,其中的模式包含“\\w”、“\\b”、“[^\\w]”等的許多變體。
更大的圖景
如何在字符串中的每個單詞后放置 * 以進行搜索?
如果您只想在每個“單詞”后添加一個星號,您可以這樣做:
<?php
$test = 'one "two" (three) -four-';
echo preg_replace('/(\w+)/', "$1*", $test);
?>
您可以使用負前瞻在單詞邊界上進行拆分,如下所示:
$array = preg_split( '/(?!\w)\b/', 'one "two" (three) -four-');
一個print_r( $array);
為您提供所需的確切輸出:
Array ( [0] => one [1] => "two [2] => " (three [3] => ) -four [4] => - )
這是一個如何在 PHP 中使用正則表達式查找單詞的示例。
<?php
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, substr($subject, 3), $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
[^\w]*(\b\w*\b)?
----- ----------
| |
| |-> Matches a word 0 or 1 time
|-> Matches 0 to many characters except [a-zA-Z0-9_]
你需要匹配!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.