Elasek
Elasek

Reputation: 123

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"?

Upvotes: 1

Views: 116

Answers (2)

Sharanya Dutta
Sharanya Dutta

Reputation: 4021

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.

Upvotes: 3

Seth
Seth

Reputation: 10454

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.

Upvotes: 0

Related Questions