开发者

Preg match question

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# 开发者_Go百科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.'


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


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;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜