使用preg_replace转换字符串

时间:2021-06-16 08:45:22

I have a string that looks something like this

我有一个看起来像这样的字符串

<a href="/team.php?team_id=521">@Arsenal Fc</a> and <a href="/profile.php?fid=50683">@Tester Alpha</a>

And I need to convert it to

我需要将其转换为

'#ArsenalFc and Tester Alpha'

'#ArsenalFc和Tester Alpha'

three things to keep in mind.

要记住三件事。

1) for links to the team.php page, The @ is converted to #

1)对于team.php页面的链接,@被转换为#

2) for links to the team.php page, string spaces are removed (Arsenal Fc to ArsenalFc)

2)对于team.php页面的链接,删除了字符串空格(Arsenal Fc to ArsenalFc)

3) for links to the profile.php page, the @ is removed

3)对于profile.php页面的链接,@被删除

Any ideas show to do this simply?

任何想法都表明要做到这一点?

1 个解决方案

#1


1  

This works for me

这对我有用

function myPregCallback($res)
{
    return '#'.str_replace(' ','',$res[1]);
}
$str = '<a href="/team.php?team_id=521">@Arsenal Fc</a> and <a href="/profile.php?fid=50683">@Tester Alpha</a>';
$newStr = preg_replace_callback('#^.+"/team\.php[^>]+>@?([^<]+)</a>#','myPregCallback',$str);
$newStr = preg_replace('#<a.+?"/profile\.php.+?>@?([^<]+)</a>#','$1',$newStr);
var_dump($newStr); //string(27) "#ArsenalFc and Tester Alpha" 

This could of course be simpler if the explicit checks for "team.php" and "profile.php" weren't necessary.

如果不需要明确检查“team.php”和“profile.php”,这当然可以更简单。

#1


1  

This works for me

这对我有用

function myPregCallback($res)
{
    return '#'.str_replace(' ','',$res[1]);
}
$str = '<a href="/team.php?team_id=521">@Arsenal Fc</a> and <a href="/profile.php?fid=50683">@Tester Alpha</a>';
$newStr = preg_replace_callback('#^.+"/team\.php[^>]+>@?([^<]+)</a>#','myPregCallback',$str);
$newStr = preg_replace('#<a.+?"/profile\.php.+?>@?([^<]+)</a>#','$1',$newStr);
var_dump($newStr); //string(27) "#ArsenalFc and Tester Alpha" 

This could of course be simpler if the explicit checks for "team.php" and "profile.php" weren't necessary.

如果不需要明确检查“team.php”和“profile.php”,这当然可以更简单。