views:

40

answers:

2

Hello,

I'm sure someone already asked this question, but after searching for more than 1 hour on google, I decided to ask my question here.

I want to itterate over an array excisting of different strings/texts. These texts contain strings with both ##valuetoreplace## and #valuetoreplace#

I want to make to preg_matches:

$pattern = '/^#{1}+(\w+)+#{1}$/';
if(preg_match($pattern, $value, $matches, PREG_OFFSET_CAPTURE))
{
   // do something with the #values#
}

AND

$pattern = '/^#{2}+(\w+)+#{2}$/';
if(preg_match($pattern, $value, $matches, PREG_OFFSET_CAPTURE))
{
   //do something with the ##value##
}

This works great. Now my only problem is as follows:

When i have a string like

$valueToMatch = 'proceding text #value#';

My preg_match cant find my value anymore (as i used a ^ and a $).

Question: how can i find the #value# and the ##value##, without having to worry if these words are in the middle of a (multi-line) value?

*In addition: What i want is to find patterns and replace the #value# with a db value and a ##value## with a array value. For example:

$thingsToReplace = 'Hello #firstname# #lastname#, 
How nice you joined ##namewebsite##.';

should be

'Hello John Doe, 
How nice you joined example.com.'
+1  A: 

Try this: /##([^#]+)##/ and /#([^#]+)#/, in that order.

Asaph
I already tried this one. The only problem is. That in this case ##value## is correct too!, as #value# is part of [#]#value#[#]
atjepatatje
In that case, run the regex that replaces `##valuetoreplace##` *first* so that those ones will be all gone, and *then* run the regex that replaces `#valuetoreplace#`. If you do it in that order, you won't have the problem you described above, because all the instances of `##valuetoreplace##` will be gone.
Asaph
Thats a good idea. Thank you Asaph
atjepatatje
A: 

Maybe nice to know for other visitors how i did it:

foreach($personalizeThis as $key => $value) 
{
   //Replace ##values##
   $patternIniData = '/#{2}+(\w+)#{2}/';
   $return = 'website'; //testdata
   $replacedIniData[$key] = preg_replace($patternIniData, $return, $value);

   //Replace #values#
   $pattern = '/#{1}+(\w+)#{1}/';  
   $return = 'ASD'; //testdata
   $replacedDbData[$key] = preg_replace($pattern, $return, $replacedIniData[$key]);
}

return $replacedDbData;

atjepatatje