nodeffect
nodeffect

Reputation: 1840

Replace string with multiple variation

I would like to replace some text in a string, however, it has multiple variation.

I have multiple string to replace and I'm looping it to replace it one by one.. for example..

$string1 = 'select * from table where id = :id';
$string2 = 'select * from table where id =:id';
$string3 = 'select * from table where id =  :id';

and so on...

I'm tyring to replace "id = :id" with "id in (:id)". So for $string1, the results should be 'select * from table where id in (:id)' and the same for other strings.

However, each variable are different, this id = :id could be id=:id or id= :id... and some has different spacing...

currently, Im using this code below, but didnt realize, some of the variables has more than one spaces...

$sql = str_replace(array("=:id", "= :id"), " in (:id)", $string);

Is is possible to do this without replacing each of the variable manually by removing excessive spaces? I'm trying to avoid doing it manually because i'm getting those variable from the database and some people would input to the database with excessive spaces and I have no control of it.

Upvotes: 2

Views: 115

Answers (1)

user2342558
user2342558

Reputation: 6731

You may use preg_replace to replace them all independently of how many spaces they contains:

$sql = preg_replace("/ *= *:id/", " in (:id)", $string);

You can try it in this live demo.

Upvotes: 3

Related Questions