yzhang
yzhang

Reputation: 165

php preg replace same string multiple times in a long string

I have a long string

$str = "#10:19.out.#7:970.in.#8:19.out.#7:3128.in.#10:101.out.#7:3131.in.#15:19.out.#7:170917.in.#10:4517.out.#7:170909.in.#12:17593"

If I use pattern

$pattern = "/out\..*in/"
$replacement = "";
$path = preg_replace($pattern, $replacement, $str);

Then the output is #10:19..#12:17593

Which is the longest match of my pattern.

I want to replace each match in the string, and get result like

#10:19.#8:19.#10:101.#15:19.#10:4517.#12:17593

Could anyone help me to solve the issue?

Upvotes: 2

Views: 339

Answers (2)

Udit Trivedi
Udit Trivedi

Reputation: 246

$str = "#10:19.out.#7:970.in.#8:19.out.#7:3128.in.#10:101.out.#7:3131.in.#15:19.out.#7:170917.in.#10:4517.out.#7:170909.in.#12:17593";

$pattern = "/out\..*?in./";
$replacement = "";
$path = preg_replace($pattern, $replacement, $str);

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

Make the quantifier ungreedy. Add a ? immediately after the *.

Upvotes: 1

Related Questions