Gowtham Ganesan
Gowtham Ganesan

Reputation: 91

Replace all the occurrence even with regex php

I need to replace all the occurrence of the string World [*] : with 2000.

Output: 20002000hello

How can I achieve that? I am currently using the below code but it is not working.

preg_replace("/World [(.*?)] : /", "2000", "World [23] : World[125] : hello",-1)

Upvotes: 0

Views: 48

Answers (3)

Muhammed Hafil
Muhammed Hafil

Reputation: 175

$str = "World [23] : World [125] : hello";
$str = preg_replace("/World (.*?) /", "2000", $str);
print $str;

Upvotes: 1

Bidoubiwa
Bidoubiwa

Reputation: 960

I have this

/(World \[.*?\] : )/

https://regex101.com/r/vbqD7a/1

Upvotes: 1

anubhava
anubhava

Reputation: 785651

You can use:

$out = preg_replace('/World\s*\[.*?\] : /', "2000", "World [23] : World[125] : hello");
//=> 20002000hello

[ and ] are special regex meta characters that need to escaped and make space after World optional with 0 or more matches.

Upvotes: 1

Related Questions