[英]How can i remove particular string after the specified string using regex in php?
[英]How do i remove last particular string using regex?
嗨,我有像下面的字符串,
$aa = "Ability: N/S,Session: Session #2: Tues June 14th - Fri June 24th (9-2:00PM),Time: 10:30am,cname: karthi";
$aa = "Ability: N/S,Session: Session #1: Tues May 31st - Fri June 10th (1-5:30PM),Time: #1 only: 1:30pm,cname: ravi";
$aa = "Ability: N/S,Session: Session #1: Tues May 31st - Fri June 10th (1-5:30PM),Time: #1 only: 1am,cname: mathi";
我需要编写单个正则表达式来从“,cname:”到最后删除特定字符串。 我需要输出像,
$aa = "Ability: N/S,Session: Session #2: Tues June 14th - Fri June 24th (9-2:00PM),Time: 10:30am";
$aa = "Ability: N/S,Session: Session #1: Tues May 31st - Fri June 10th (1-5:30PM),Time: #1 only: 1:30pm";
$aa = "Ability: N/S,Session: Session #1: Tues May 31st - Fri June 10th (1-5:30PM),Time: #1 only: 1am";
我怎么能在正则表达式中这样做?
你不需要正则表达式。 您可以使用strpos()查找',cname:'的索引,然后使用substr()直到该索引。
<?php
$aa = "Ability: N/S,Session: Session #1: Tues May 31st - Fri June 10th (1-5:30PM),Time: #1 only: 1am,cname: mathi";
$pos = strpos($aa, ',cname:');
$bb = substr($aa, 0, $pos);
echo $bb, "\n";
但是如果你因为某种原因坚持使用正则表达式,你会想要使用preg_replace() :
<?php
$aa = "Ability: N/S,Session: Session #1: Tues May 31st - Fri June 10th (1-5:30PM),Time: #1 only: 1am,cname: mathi";
$bb = preg_replace('#,cname:.*$#', '', $aa);
echo $bb, "\n";
如果您不想修改字符串,可能需要使用preg_match() :
<?php
$aa = "Ability: N/S,Session: Session #1: Tues May 31st - Fri June 10th (1-5:30PM),Time: #1 only: 1am,cname: mathi";
if (preg_match('#^(.+),cname:.*$#', $aa, $match)) {
echo $match[1], "\n";
}
/^(.*),cname:.*;$/
这个正则表达式生成的第1组($ 1)将为您提供所需的结果。
如果您有多个,cname:...
并且只想删除最后一个,请使用:
$aa= preg_replace('/,cname:.*?$/', '', $aa);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.