Skip to content
Advertisement

How can i replace all specific strings in a long text which have dynamic number in between?

I am trying to replace strings contains specific string including a dynamic number in between. I tried preg_match_all but it give me NULL value

Here is what i am actually looking for with all details:

In my long text there are values which contains this [_wc_acof_(some dynamic number)] , i.e: [_wc_acof_6] i want to convert them to $postmeta['_wc_acof_14'][0]

This can be multiple in the same long text.

I want to run through with this logic:

1- First i get all numbers after [_wc_acof_ and save them in array by using preg_match_all as guided here get number after string php regex

2- Then i run a foreach loop and set my arrays for patterns and replacements with that number i.e:

foreach ($allMatchNumbers as $MatchNumber){
  $key = "[_wc_acof_" . $MatchNumber. "]";
  $patterns[] = $key;
  $replacements[] = $postmeta[$key][0];
}

3- Then i do replace with this echo preg_replace($patterns, $replacements, $string);

But i am unable to get preg_match_all it gives me NULL where i tried below

preg_match_all('/[_wc_acof_/',$string,$allMatchNumbers );

Please Help? i am not sure if preg_grep is better than this?

Advertisement

Answer

It seems you want to process the input in stages, to obtain all the numbers in specific lexical context first, and then modify the user input using some lookup technique.

The first step can be implemented as

preg_match_all('~[_wc_acof_(d+)]~', $text, $matches)

that extracts all sequences of one or more digit in between [_wc_acof_ and ] into Group 1 (you can access the values via $matches[1]).

Then, you may fill the $replacements array using these values.

Next, you can use

preg_replace_callback('~[_wc_acof_(d+)]~', function($m) use ($replacements){
    return $replacements[$m[1]];
}, $text)

See the PHP demo:

<?php
$text = '<p>[_wc_acof_6] i want to convert this and it contains also this [_wc_acof_9] or can be this [_wc_acof_11] number can never be static</p>';

if (preg_match_all('~[_wc_acof_(d+)]~', $text, $matches)) {

    foreach($matches[1] as $matched){
        $replacements[$matched] = 'NEW_VALUE_FOR_'.$matched.'_KEY';        
    }
    print_r($replacements);
    echo preg_replace_callback('~[_wc_acof_(d+)]~', function($m) use ($replacements){
        return $replacements[$m[1]];
    }, $text);
}

Output:

Array
(
    [0] => 6
    [1] => 9
    [2] => 11
)
NEW_VALUE_FOR_6_KEY i want to convert this and it contains also this NEW_VALUE_FOR_9_KEY or can be this NEW_VALUE_FOR_11_KEY number can never be static
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement