[英]PHP regex for a specific pattern of text
在我的网站上,我插入了当年在主体中创建一个项目的年份,并将其替换为“六年前”(或时间长短)。
所以在我的内容中,我有:
我们从1998年开始从事业务,并于[2011年]之前制作了这种包装设计。
我正在尝试使用正则表达式将2011年放入变量中,以便稍后进行搜索和替换,但无法弄清楚。 每页只有一个实例。 我可以进行搜索和替换,这只是正则表达式,我从来没有动过头。
为了解决以下问题-年份是可变的,这就是为什么我要使用正则表达式。
例
$bodycontent = <p>We've been in business since 1998
and produced this logo design [2002] years ago.</p>
要么
$bodycontent = <p>We've been in business since 1998
and produced this website design [2016] years ago.</p>
因此,我将花括号中的年份放入正则表达式为$ then的变量中,然后从当前年份中减去该年份以得出$ age(由另一个函数转换为单词)
$bodycontent = str_replace("[".$then."]",$age,$bodycontent)
我试过了
preg_match("[\d{4}]",$bodycontent,$found);
但它会返回第一个日期,而不是大括号中的那个。
使用函数preg_replace_callback()
:
$bodycontent = preg_replace_callback('~\[(\d{4})\]~', function($match) {
return (date('Y') - $match[1]) . " ago";
}, $bodycontent);
如果这是我的项目,那么我可能会利用一个查找字词数组进行preg_replace_callback()
调用,并在括号中的日期“超出范围”时进行后备替换。
*请务必在适当的时候将year
复数。
*我模式中的第二个]
不需要转义,但是如果您认为它可以提高可读性,则可以添加它。
*我也在years ago
匹配,因此替换文字在所有情况下都有意义; 您可能希望在原始输入文本中删除此尾随文本。
代码:( 演示 )
$bodycontent = "<p>We've been in business since 1998 and produced this logo design [1995] years ago.</p>\n";
$bodycontent .= "<p>We've been in business since 1998 and produced this website design [2018] years ago.</p>\n";
$bodycontent .= "<p>We've been in business since 1998 and produced this website design [2017] years ago.</p>\n";
$bodycontent .= "<p>We've been in business since 1998 and produced this website design [2016] years ago.</p>";
$lookup=['less than a','one','two','three','four','five','six','seven','eight','nine',
'ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'
]; // extend as needed
$bodycontent = preg_replace_callback('/\[(\d{4})] years ago/', function($m)use($lookup){
$diff=date('Y')-$m[1];
if(isset($lookup[$diff])){
return $lookup[$diff].' year'.($diff>1?'s':'').' ago';
}else{
return "in {$m[1]}"; // out of lookup range, use backup text
}
}, $bodycontent);
echo $bodycontent;
输出:
<p>We've been in business since 1998 and produced this logo design in 1995.</p>
<p>We've been in business since 1998 and produced this website design less than a year ago.</p>
<p>We've been in business since 1998 and produced this website design one year ago.</p>
<p>We've been in business since 1998 and produced this website design two years ago.</p>
假设此格式为[2002] years
,则可以使用此正则表达式作为替代方法:
说明
\[ # Match [ ( # Capturing group \d{4} # Match 4 digits ) # Close capturing group \] # Match ] years # Match `whitespace`years
然后,您可以使用preg_match来匹配组1中的年份,以年为单位计算差异,并执行单数或复数格式。
例如:
$bodycontent = "<p>We've been in business since 1998 and produced this logo design [2002] years ago.</p>";
preg_match('/\[(\d{4})\] years/', $bodycontent, $matches);
$years = date('Y') - $matches[1];
$result = sprintf("%s year%s",
$years,
$years === 1 ? "": "s"
);
$bodycontent = str_replace($matches[0], $result, $bodycontent);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.