0

I have multi-line string with some variables like $Item_#1_Value$, $Item_#2_Value$, and so on. I would like to replace (case in-sensitive) all these instances with real values, which is not a problem with str_ireplace().

The problem is I need to remove also all spaces which may (or may not) be adjacent to these variables. The other spaces, not adjacent to variables, I need to not touch.

For example: If $item_#1_Value$ is 1234, so strings: ABC$item_#1_Value$QWERT, ABC $ITEM_#1_VALUE$ QWERT, ABC $item_#1_Value$ QWERT all needs to be replaced to ABC1234QWERT.

I have understood it should be preg_replace(...) used instead of str_ireplace(...), but I cannot realize what regexp pattern should I use.

1 Answer 1

1

One way to do it with regular expressions would be to match your tag with optional surrounding multiple whitespace:

\s*\$item_#1_Value\$\s*

Demo

PHP Code

<?php
$strings[] = 'ABC$item_#1_Value$QWERT';
$strings[] = 'ABC $ITEM_#1_VALUE$ QWERT';
$strings[] = 'ABC $item_#1_Value$ QWERT';
foreach ($strings as $string) {
    $string = preg_replace('/\s*\$item_#1_Value\$\s*/i', "1234", $string);
    echo $string.PHP_EOL;
}

Demo

Result

ABC1234QWERT

ABC1234QWERT

ABC1234QWERT

Sign up to request clarification or add additional context in comments.

4 Comments

Your first answer is not suitable, it will remove ALL spaces, not only adjacent. I did not provide samples with those spaces, but I have mentioned it in my explanation. Second suggestion seems like exactly what I need, thank you, will go to test.
@SergeS I seem to have missed that part, sorry. I've updated the answer. Notice the second answer is edited too to meet your needs.
Works perfectly! Thank you again.
Happy to help my friend.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.