如何替换变量中的数据URL

时间:2019-01-17 16:06:56

标签: php blogger

如何替换网址的一部分? 我尝试使用str_replace。

示例:

$urlTarget = 'https://www.example.net/';
$myDomain = 'https://www.mydmoain.net/';

$data = 'Some parents believe that baby walkers can help their baby's growth and development, especially helping the children to walk faster. However, is it true that baby walkers can help child development? Or even dangerous? Let's take a look at the pros and cons of baby walkers <a href="http://www.example.net/2018/01/news-doctor.html">below</a>';
$replace = str_replace($urlTarget,$myDomain,$data);

结果:

"Some parents believe that baby walkers can help their baby's growth and development, 
especially helping the children to walk faster. However, is it true that baby walkers can help 
child development? Or even dangerous? Let's take a look at the pros and cons of baby walkers 
<a href='https://www.mydmoain.net/2018/01/news-doctor.html'>below</a>"

我要删除2018/01/并将结果更改为:

$data = 'Some parents believe that baby walkers can help their baby's growth and development, especially helping the children to walk faster. However, is it true that baby walkers can help child development? Or even dangerous? Let's take a look at the pros and cons of baby walkers <a href="http://www.mydmoain.net/search?q=new-doctor">below</a>';

注意:-,我需要在包含不同日期的URL上执行此操作。

1 个答案:

答案 0 :(得分:1)

此答案将做出许多假设,因为您在整个问题中都不十分精确。

我将假设原始的URL和所需的URL都使用“ http”而不是“ https”。您在问题中的两者之间来回走动。

我将假设href标记中的<a>属性在原始和结果中都用双引号引起来。您的问题在原文中包含双打,在结果中包含单打。

我要假设,即使您的问题在期望的结果中包含“ search?q = new-doctor”,但当输入中包含“ news-doctor.html”时,您实际上还是想要“ search?q = news-doctor” “

我将假定原始URL的日期部分始终是4位数字的年份,后跟一个斜杠,再加上2位数字的月份。

请在询问将来的问题时注意细节,因为它们很重要。尤其是在这种情况下,答案将使用正则表达式的情况下。

我们将用于获得所需结果的函数是preg_replace()

$urlTarget = "http://www.example.net";
$myDomain = "http://www.mydmoain.net";

$data = "Some parents believe that baby walkers can help their baby's growth and development, especially helping the children to walk faster. However, is it true that baby walkers can help child development? Or even dangerous? Let's take a look at the pros and cons of baby walkers <a href=\"http://www.example.net/2018/01/news-doctor.html\">below</a>";

$resultUrl = preg_replace("@".$urlTarget."/\d{4}/\d{2}/(.*)\.(.*)\"\>@", $myDomain."/search?q=$1\">", $data);

echo $resultUrl;

正则表达式细目:

@:启动定界符。不使用典型的/,这样我们就不必转义URL中的斜杠

$urlTarget:我们只想匹配以“ http://www.example.net”开头的网址

/\d{4}:斜杠后跟正好4位数字

/\d{2}:斜杠后跟正好2位数字

/(.*):斜杠后跟任意数量的任何字符(这些字符在捕获组中,因此我们可以在替换字符中引用它们)

\.:点(转义)(用于将文件分为名称和扩展名)

(.*):任意数量的任何字符(示例中为扩展名“ html”)

\">:双引号(转义),后跟大于>,以捕获<a>标签的结尾

@:结束定界符

DEMO