EnderAdel
EnderAdel

Reputation: 55

How to replace text without caring for spaces between words in php

I want to know, how can I replace the text with something else without the spaces affecting the process.
("Hi, I'm here!" Will be replaced with "bye")
Like this(Value ==> ReplacedValue):

Hi,I'mhere!                  ==>   bye
Hi, I'm here!                ==>   bye
Hi,  I'm here!               ==>   bye
Hi  ,     I'm        here!   ==>   bye

Now using str_ireplace (str_ireplace("TheOriginalWord", "TheReplacement", $data)) won't do what I want, it'll do this:

Hi, I'm here!                ==>   bye
Hi,  I'm here!               ==>   Hi,  I'm here!
Hi  ,     I'm        here!   ==>   Hi  ,     I'm        here!

Upvotes: 0

Views: 116

Answers (2)

Jeto
Jeto

Reputation: 14927

Barmar's answer is good, but just in case you need something reusable, you could use the following function:

function replace_spaceless(string $subject, string $from, string $to): string
{
  $pattern = '/' . preg_replace('/(?<!^)\s*\b\s*(?!$)/', '\\s*', preg_quote($from, '/')) . '/';
  return preg_replace($pattern, $to, $subject);
}

This is basically str_replace except it ignores spaces. To do so, it builds a regular expression replacing all word boundaries (except at beginning/end of the string) by \s*, and pass it to preg_replace.

Demo: https://3v4l.org/o5om1

Upvotes: 0

Barmar
Barmar

Reputation: 780787

Use a regular expression.

preg_replace('/Hi\s*,\s*I\'m\s*here!/i', "bye", $data);

\s* matches zero or more spaces. If you only want to match one or more spaces, use \s+ instead.

Upvotes: 1

Related Questions