简体   繁体   中英

Replace word when stand alone

I have a query:

select last_name as lastname from table

and I want to change the "as" keyword to capital (for the rest of my script to run properly), but only when its alone.

when i use this script:

$toupper = str_replace(array("select","from","where","order by", "group by", "as"),
                  array("SELECT","FROM","WHERE","ORDER BY", "GROUP BY","AS"),$query);

It will also change the other strings that have "as". so it becomes this:

SELECT lASt_name AS lAStname FROM table

how can i replace the stand alone keyword "as" to "AS"?

You should a regular expression to match whole words only:

$toupper = preg_replace("/\bas\b/", "AS", $query);

Using a word boundary before and after the word is more effective than using a space at the same positions because it matches all non-word characters like space, line-break, hyphen and so on. You may read about the anchor \\b here .

You can use almost the exact code you currently have.

Since AS statement always has a space before and after it, just modify str_replace slightly to have a space before and after as and AS , like so:

$toupper = str_replace(array("select","from","where","order by", "group by", " as ",),array("SELECT","FROM","WHERE","ORDER BY", "GROUP BY"," AS "),$query);

The result is:

SELECT last_name AS lastname FROM table

This way you can keep the code you have virtually identical.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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