[英]Matching Word with regular expression
I have the following text file: 我有以下文本文件:
...
"somewords MYWORD";123123123123
"someother MYWORDOTHER";456456456456
"somedifferent MYWORDDIFFERENT";789789789
...
I need to match the word MYWORD, MYWORDOTHER, MYWORDDIFFERENT and then substitute the space before this word with ";". 我需要匹配单词MYWORD,MYWORDOTHER,MYWORDDIFFERENT,然后用“;”代替该单词之前的空格。 Someone can figure out a regex?
有人可以找出正则表达式吗?
I have done something like that: 我做了这样的事情:
+[^ ][^ ][^ ][^ ][^ ][^ ][^ ]";
but this works only with a specific word length. 但这仅适用于特定的字长。 I need to modify to get any word of any length.
我需要修改以获取任何长度的单词。
Any help? 有什么帮助吗?
why don't you str_replace()
? 你为什么不
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);
Maybe this: 也许这样:
$result = preg_replace('/([ ])(\w+)";/im', ';$2";', $subject);
in: 在:
"somewords MYWORD";123123123123 "someother MYWORDOTHER";456456456456 "somedifferent MYWORDDIFFERENT";789789789
out: 出:
"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
}
Edit : 编辑 :
Alright, I made a typo in the original answer. 好吧,我在原始答案中打了错字。
Now corrected with a codepad: http://codepad.org/leQHTuFR 现在使用键盘进行了更正: http : //codepad.org/leQHTuFR
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.