preg_replace url获取id

时间:2013-10-01 13:11:26

标签: php url curl preg-replace

我想用php中的curl替换页面中的url。

网址就像;

http://www.externalwebsite.com/title-of-the-page-192345.htm

我使用$url = preg_replace('~a href="([a-z,.\-]*)~si', '"', $url);

这正确地给了我id,但是如果在title

中使用了任何其他数字字符 例如

;

http://www.externalwebsite.com/title-of-the-3-page-192345.htm

它给了我;

3-page-192345

输出。在这种情况下,如何获取页面的正确ID。谢谢。

更新

我需要替换curl从其他网站获取的页面中的网址。网址如上所述。

<?php

$ch = curl_init ("http://www.externalwebsite.com/index.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$page = curl_exec($ch);
preg_match('#<div class="headline"[^>]*>(.+?)</div>#is', $page, $matches);
foreach ($matches as &$match) {
    $match = $match;
}
$html=$matches[1];   
$html = preg_replace('~a href="([a-z,.\-]*)~si', '"', $html); //NEED TO CHANGE THIS                                         

    echo $html;

?>

没有任何preg_replace的curl之后页面的Html代码是这样的;

     <div class="swiper-slide red-slide">
    <div class="title"><a href="http://www.externalwebsite.com/title-of-the-3-page-192345.htm" class="image">
<img src="http://www.externalwebsite.com/d/news/94406.jpg"/></a></div></div>

在preg_replace命令之后,这个html必须是这样的:

<div class="swiper-slide red-slide">
        <div class="title"><a href="http://www.mywebsite.com/read_curl_page.php?id=192345" class="image">
    <img src="http://www.externalwebsite.com/d/news/94406.jpg"/></a></div></div>

1 个答案:

答案 0 :(得分:1)

使用preg_match而不是preg_replace

<?php

  $matches = array();
  $url ='http://www.mywebsite.com/title-of-the-page-192345.htm';
  preg_match('#http://(.*?)/(.*?)-([0-9]+).htm#', $url, $matches);
  print_r($matches);
  echo $matches[2]; //this will print title of page
  echo $matches[3]; //this will print id of page
  echo $matches[1]; //this will domain
?>

输出:

Array ( [0] => http://www.mywebsite.com/title-of-the-page-192345.htm [1] => www.mywebsite.com [2] => title-of-the-page [3] => 192345 )

Preg_replace顾名思义替换你想要的字符串获取一些字符串信息。子模式可以在$matches数组中获取这些信息。数字的子模式为([0-9]+),表示至少有1个数字。