简体   繁体   English

正则表达式查找并替换

[英]Regular Expressions find and replace

I am having problems with RegEx in PHP and can't seem to find the answer. 我在使用RegEx的PHP中遇到问题,似乎找不到答案。

I have a string, which is 3 letters, all caps ie COS. 我有一个字符串,它是3个字母,全部大写,即COS。

the letters will change but always be 3 chars long and in caps, it will also be in the center of another string, surrounded by commas. 字母会改变,但始终为3个字符,并且大写,也将位于另一个字符串的中心,并用逗号包围。

I need a regEx to find 3 caps letter inside a string and cahnge them from COS to 'COS' (im doing this to amend a sql insert string) 我需要一个regEx在一个字符串中找到3个大写字母,然后将它们从COS更改为“ COS”(我这样做是为了修改sql插入字符串)

I can't seem to find the regEx unless i use spercifit letter but the letters will change. 除非我使用spercifit字母,否则我似乎找不到regEx,但是字母会发生变化。

I need something along the lines of [Az]{3} then replace with '[AZ]' (I know this isnt anywere near correct, just shorthand) 我需要一些类似于[Az] {3}的内容,然后替换为'[AZ]'(我知道这几乎是正确的,只是速记)

Anyone any suggestions? 有任何建议吗?

Cheers 干杯

EDIT: 编辑:

Just wanted to add incase anyone comes accross this question at a later date: 只是想补充一下,以防以后有人遇到这个问题:

the sql insert string (provided from an external source and ftp's to my server daily) contained the 3 capital string twice, once with commas and once with out so I had to also remove the double commas added from the first regEx sql插入字符串(每天从外部源和ftp到我的服务器提供)包含3个大写字符串,两次用逗号,一次用不了,所以我还必须删除从第一个regEx添加的双逗号。


$sqlString = preg_replace('/([A-Z]{3})/', "'$1'", $isqlString);
$sqlString = preg_replace('/\'\'([A-Z]{3})\'\'/', "'$1'", $sqlStringt);

Thanks everyone 感谢大家

You were actually very close. 你真的很亲密。 You could use: 您可以使用:

echo preg_replace('/([A-Z]{3})/', "'$1'", 'COS'); //will output 'COS'


For MySQL statements I would advise to use the function mysql_real_escape_string() though. 对于MySQL语句,我建议使用mysql_real_escape_string()函数。

$string = preg_replace('/([A-Z]{3})/', "'$1'", $string);

http://php.net/manual/zh/function.preg-replace.php

Assuming it's like you said, "three capital letters surrounded by commas, eg 假设您说的是:“三个大写字母用逗号包围,例如

Foo bar,COS,Foo Bar Foo bar,COS,Foo Bar

You can use look-ahead and look-behinds and find the letters: 您可以使用先行查找和后退查找字母:

(?<=,)([A-Z]{3})(?=,)

Then a simple replace to surround with single quotes will be adequate: 然后,用单引号引起来的简单替换就足够了:

'$1'

All together, Here's it working . 总之, 这就是工作

preg_replace('/(^|\b)([A-Z]{3})(\b|$)/', "'${2}'", $string);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM