How to preg_replace_all on a lot of data

I'm just doing a script update to replace all MODX chunk labels with a newer format:

Old: [~123~]

New: [[~123]]

(of course 123 is an example - there are many different numbers)

Also I wanted to replace all custom old snippets with newer ones:

Old snippet format:

[!MySnippetName? &param1=`value1` &param2=`value2` !]

      

New:

[[!MySnippetName? &param1=`value1` &param2=`value2` ]]

      

(of course &param1=value1 &param2=value2

is just an example and it differs from real snippets)

How do I use the preg_replace function to create global notes? I had to create like this:

$doc[ 'content' ] = $this->preg_replace_all(
        array(
                '/\[~([0-9]+)~\]/',
                '\[!LatestUpdates(.*)!\]',
                '\[!ArticleSummary(.*)!\]',
            ), array(
                '[[~\1]]',
                '[[!LatestUpdates\1]]',
                '[[!ArticleSummary\1]]',
            ),
            $doc[ 'content' ]
        );

      

preg_replace_all function :

private function preg_replace_all( $find, $replacement, $s )
{
    while(preg_match($find, $s)) {
        $s = preg_replace($find, $replacement, $s);
    }
    return $s;
}

      

But that won't work. Please help sort out the problem. Thanks in advance.

+3


source to share


2 answers


The preg_replace

function already performs global replacement, and since only substrings are replaced, you do not need to check for the existence of these substrings with preg_match

.

You can narrow down three templates to just one template:

$pattern = '/\[(?|(!LatestUpdates|!ArticleSummary)(.*?)!]|(~)([0-9]+)~])/';
$replacement = '[[$1$2]]';
$doc['content'] = preg_replace($pattern, $replacement, $doc['content']);

      

This pattern uses the branch reset feature , which allows capture groups to have the same number in each alternative.



If possible (if it doesn't change the tags you want to keep) you can do the same with strtr

:

$doc['content'] = strtr($doc['content'], array('[!'=>'[[!', '[~'=>'[[~', '~]'=>']]', '!]'=>']]'));

      

Please note, if you can use it, feel free to, as this method is much faster.

+4


source


Why are you using PHP for this - did you write a plugin to convert all Evolution tags to Revolution format whenever the page is parsed?

If this is the case, it is inefficient and it would be better to replace all the tags in the database where content, templates, chunks, etc. are stored.

You can do it easily using a query like this:



UPDATE modx_site_content SET content = REPLACE(content, '[!', '[[!');

      

Repeat this for all other open and close tags and other database tables.

Make a backup of your database before trying this ...

+1


source







All Articles