当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Replacing a string using preg_match

问题描述:

I'm having trouble using preg_match to find and replace a string. The string of interest is:

<span style="font-size:0.6em">EXPIRATION DATE: 04/30/2011</span>

I need to target and replace the date, "04/30/2011" with a different date. Can someone throw me a bone a give me the regular expression to match this pattern using preg_match in PHP? I also need it to match in such a way that it only replaces up to the first closing span and not closing span tags later in the code, e.g.:

<span style="font-size:0.6em">EXPIRATION DATE: 04/30/2011</span><span class="hello"></span>

I'm not versed in regex, and although I've spent the last hour trying to learn enough to make this work, I'm utterly failing. Thanks so much!

EDIT: As you can see this has gotten me exhausted. I did mean preg_replace, not preg_match.

网友答案:

If you're after a replacement, consider using preg_replace(), something like

preg_replace('@(\d{2})/(\d{2})/(\d{4})@', '<new date>', $string);
网友答案:

How about this:

$toBeFoundPattern = '/([0-9][0-9])\/([0-9][0-9])\/([0-9][0-9][0-9][0-9])/';
$toBeReplacedPattern = '$2.$1.$3';

$inString = '<span style="font-size:0.6em">EXPIRATION DATE: 04/30/2011</span>';

// Will convert from US date format 04/30/2011 to european format 30.04.2011
echo preg_replace( $toBeFoundPattern, $toBeReplacedPattern, $inString );

and prints

EXPIRATION DATE: 30.04.2011

Patterns always begin and end with identical so called delimiter characters. Often the character / is used.

$1 references the string, which matched the first string matched by ([0-9][0-9]), $2 references be (...) and $3 the four letters matched by the last (...).

[...] matched a single character, which is one of those listed inside the brackets. E.g. [a-z] matches all lower case letters.

To use the special meaning character / inside of a pattern, you need to escape it by \ to make it be the literal slash character.

Update: Using {..} as pointed out below is shorthand for repeated patterns.

网友答案:

Regex should be:

(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d

If you want to only match one instance, this is OK. For multiple instances, use preg_match_all instead. Taken from http://www.regular-expressions.info/regexbuddy/datemmddyyyy.html.

Edit: are you looking to just search and replace inside a PHP script or do you want to do some javascript live replacement?

分享给朋友:
您可能感兴趣的文章:
随机阅读: