Question

Can anyone please help me with this...I'm not very good with regular expressions and I'm banging my head since days!

In Smarty I have this array o values included in curly brackets captured in variable $str:

{capture assign=str}{literal}
{label1: \"value1\",label2: \"value2\", label3: \"value3\",label4: \"value4\"},
{label1: \"value1b\",label2: \"value2b\", label3: \"value3b\",label4: \"value4b\"},
...
{/literal}{/capture}

I need to overwrite a series of labels and values (from { to } ) if label1: \"value1\" match my string.

This is what I got so far...

{capture assign=foo_regex}{literal}/[{label1:\s*\\"{/literal}{$smarty.get.value1}{literal}\\",\s*label2:\s*\\"{/literal}{$smarty.get.value2}{literal}\\"].*[}]/g{/literal}{/capture}
{capture assign=foo_replace}{literal}{-my new string-}{/literal}{/capture}
{$str|regex_replace:$foo_regex:$foo_replace}

any wizard out there please help ? Thank you in advance !

Update: I came out with the correct expression, but it's not working with Smarty regex...what am I doing wrong? http://regexr.com?30dnp

Update2 @ lorenzo: when label1: \"value1\",label2: \"value2\" matches my string I overwrite it with a new string from { to } like this {label1: \"value1\",label2: \"value2\",label3: \"value3\",label4: \"value4\"}

What it does: check if stored value1 and value2 match my test string, if positive -> update all other values (4,5,6) with my new string values.

Hope now it's clearer what I want to achieve.

Was it helpful?

Solution 2

Solution (for others who may need a hint on the subject):

  1. got the correct php formatting for my expression with this useful online tool: http://www.techeden.com/regex

  2. then created a php snippet (udt) in my CMSMS admin to replace from { to } when match is found:

    $result = preg_replace('/.*(?:label1\: \\\\\"'.$params['value1'].'\\\\\").*(?:label2\: \\\\\"'.$params['value2'].'\\\\\").*[}]/m', $params['replace'], $params['str']);
    

OTHER TIPS

Should you be using Smarty3, you could stop playing with strings and start using proper structures.

{* ordinary array, could've been assign()ed *}
{$labels = [
  "label1" => "value1",
  "label2" => "value2",
  "label3" => "value3",
  "label4" => "value4"
]}

{if $labels.label3 == 'value3'}
 {$labels.label3 = 'hello world'}
{/if}

{$labels|json_encode|escape}

would output

{"label1":"value1","label2":"value2","label3":"hello world","label4":"value4"}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top