开发者

How can I specify "any character" including double quotes, gt, lt, equal

In php I have next text:

$text='<div id="my_date_div"
                            year="2010"
                            month="12"
                            day="07"
                            hour="00"
                            minute="00"
                        >
                  <span id="my_span_days">dys</span>
                            <span id="my_span_hours">hrs</span>
                                                 </div>'

I would like to perform a preg_replace() to keep only certain values of the upper text, for example year (2010) and hour(00).

I perform a lookup for /year=\"/ and for /hour=\"/, however I dont know how to remove the ot开发者_运维问答her text which I dont want since the expresion [.+\s+]* does not match characters like " or <

What I have is

$regex = "/[.+\s+]*year=\"(\d+)\"[.+\s+]*hour=\"(\d+)\"[.+\s+]*$/";
$regrep = "$1 $2";
echo preg_replace($regex, $regrep, $text);

Any hint? Thanks


You can use preg_match_all to match the text you want and replace the input string with the matched part:

preg_match_all('/((?:year|hour)\s*=\s*"\d+")/m',$text,$m);
$text = implode("\n",$m[1]);

Ideone link


.+\s+ inside [] represent themselves, they have no special meaning. Thats why they don't match to " <. codaddict's answer has also one good property: order of hour year attributes in source text isn't meaningful.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜