root66
root66

Reputation: 607

preg_replace: Ignore already replaced parts

I want to replace a date pattern string (intl extension) with the corresponding input fields.

The patterns can be:

dd.MM.yy
dd.MM.yyyy
M/d/yy
M/d/yyyy
dd/MM/y
dd/MM/yyyy

My code is:

$date_pattern = 'M/d/yy';

$search = array('/[d|dd]/', '/[M|MM]/', '/[y|yy|yyyy]/');
$replace = array(
'<input type="text" name="day" size="2" maxlength="2">',
'<input type="text" name="month" size="2" maxlength="2">',
'<input type="text" name="year" size="4" maxlength="4">');

print preg_replace($search, $replace, $date_pattern);

The problem is, that "preg_replace" matches already the first replaced input field at the position:

<input t[here because of the 'y' character]pe="text" ...>

Is there any way to tell preg_replace to ignore already replaced parts?

Upvotes: 1

Views: 164

Answers (1)

anubhava
anubhava

Reputation: 785156

Your regex doesn't seem right as [d|dd] only matches d or literal |.

Better use word boundaries in your regex as this:

$search = array('/\bd{1,2}\b/', '/\bM{1,2}\b/', '/\b(?:y{1,2}|y{4})\b/i');
print preg_replace($search, $replace, $date_pattern);

Output:

<input type="text" name="month" size="2" maxlength="2">/<input type="text" name="day" size="2" maxlength="2">/<input type="text" name="year" size="4" maxlength="4">

Upvotes: 2

Related Questions