嗨我有如下字符串,
$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";
我怎么能在正则表达式中这样做?
答案 0 :(得分:1)
答案 1 :(得分:1)
你不需要正则表达式。您可以使用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";
}
答案 2 :(得分:0)
/^(.*),cname:.*;$/
此正则表达式生成的第1组($ 1)将为您提供所需的结果。
答案 3 :(得分:0)
如果您有多个,cname:...
并且只想删除最后一个,请使用:
$aa= preg_replace('/,cname:.*?$/', '', $aa);