Regex Asset Similarity to PHP's preg_replace


(Lewis) #1

According to the manual, the preg_replace keyword in Squiz 6 has “the same functionality as the preg_replace() PHP function”.

I’ve tried to use the Regular Expression assets with arrays in both the REGEX and REPLACEMENT fields, but it doesn’t seem to interpret them as no replacements take place.

I’m using the standard Squiz/PHP notation for arrays - [ “foo”, “bar”, “baz” ] and [ “1”, “2”, “3” ] for REGEX and REPLACEMENT.

Here’s the extract from PHP’s manual regarding preg_replace - " If both pattern and replacement parameters are arrays, each pattern will be replaced by the replacement counterpart."

I’m taking ‘pattern’ to be REGEX in Squiz.

Any ideas? Is this a future enhancement? Am I missing something? Can we expect to be able to use arrays in both parameters in the future? The latter would be useful, as I could see situations where things like responses from SOAP or REST could be used to substitute text on a webpage perhaps and for example.


(Iain Simmons) #2

Hi @lewis,

I believe it is already using the array syntax under the hood, which is why the Regular Expression asset allows you to enter multiple Regex and Replacements, with each being a row with corresponding input fields.

So you could add /foo/ in the Regex column input of the first row and 1 in the Replacement column input of the first row, /bar/ in the Regex column input of the second row and 2 in the Replacement column input of the second row, and so on.

Don’t forget that the ^preg_replace: modifier expects you to specify the asset ID of the Regular Expression asset, not the regex and replacements like the normal ^replace: modifier.


(Lewis) #3

Thanks for your reply @isimmons.

I saw you can add additional rows. Like you say - guess it works like and array behind the scenes.

If I don’t know ahead of time, the number of patterns and replacements, I guess I would have to set a limit - say ‘up to 10 replacements’ on an asset? I’d also have to know the number of patterns I would think?

I believe ^replace uses a subset of the PCRE?


(Iain Simmons) #4

Hi @lewis,

If you leave the number of replacements as its default (might be zero 0), then it will do all of them.

So you can just keep adding them.

Hope that helps,
iain