簡體   English   中英

用正則表達式匹配Word

[英]Matching Word with regular expression

我有以下文本文件:

...
"somewords MYWORD";123123123123
"someother MYWORDOTHER";456456456456
"somedifferent MYWORDDIFFERENT";789789789
...

我需要匹配單詞MYWORD,MYWORDOTHER,MYWORDDIFFERENT,然后用“;”代替該單詞之前的空格。 有人可以找出正則表達式嗎?

我做了這樣的事情:

 +[^ ][^ ][^ ][^ ][^ ][^ ][^ ]";

但這僅適用於特定的字長。 我需要修改以獲取任何長度的單詞。

有什么幫助嗎?

你為什么不str_replace()

$string = '"somewords MYWORD";123123123123
"someother MYWORDOTHER";456456456456
"somedifferent MYWORDDIFFERENT";789789789';

$replace = str_replace(' MYWORD', ';MYWORD', $string);
echo $replace;

鍵盤示例

這未經測試,但是應該可以替換引號中最后一個單詞之前的空格...

preg_replace('/(".+) (\w+";\d+)/',"$1;$2", $your_string);
preg_replace('/\s(\w+);\d/', ';$1', $text);

也許這樣:

$result = preg_replace('/([ ])(\w+)";/im', ';$2";', $subject);

在:

"somewords MYWORD";123123123123 
"someother MYWORDOTHER";456456456456 
"somedifferent MYWORDDIFFERENT";789789789

出:

"somewords;MYWORD";123123123123
"someother;MYWORDOTHER";456456456456
"somedifferent;MYWORDDIFFERENT";789789789

用這個 :

preg_replace('#"(\w+)\s+(\w+)"#',"$1;$2",$text);
while($line=fgets($file))
{
    $str=preg_replace("/ (\w)/i",";$1",$line);//use this line if you want to replace every space
    $str=preg_replace("/ (\w+)\";(\d)/i",";$1\";$2",$line);//use this line if you only want to replace the last space
    echo $str;//or wherever you want to output
}

編輯

好吧,我在原始答案中打了錯字。

現在使用鍵盤進行了更正: http : //codepad.org/leQHTuFR

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM