简体   繁体   English

preg_match_all和正则表达式

[英]preg_match_all and regex

i have page in that approx 10-15 links are there and all links are in my control and end with some words like celebrity i want to filter all links ending with that word so i have written this 我在页面中大约有10-15个链接,所有链接都在我的控制下,并以名人之类的词结尾,我想过滤所有以该词结尾的链接,所以我写了这个

    $regex='|<a.*?href="(.*_celebrity)"|';


    preg_match_all($regex,$result21,$parts);
$links=$parts[0];
foreach($links as $link){
{
    echo $link."<br>";
    mysql_query ("INSERT INTO tablea(linkssas) VALUES ('$link')");
    }

it does the job and filters all links which is ending with _celebrity but the output is not entering in database.all links are entering in one row and it is not plain it is in the form of anchor text but i want plain links in the database as i am using foreach so all links should be entered in seperate row but all rows are entering in single row and in the form of anchor like http://xyz.com/edje/jjeieied_celebrity">A</a> 它完成了工作并过滤了所有以_celebrity结尾的链接,但输出未输入到database.all链接都进入了一行,并且它不是简单的以锚文本的形式出现,但是我想要数据库中的纯链接当我使用foreach时,所有链接都应在单独的行中输入,但所有行都应以锚定的形式输入,例如http://xyz.com/edje/jjeieied_celebrity">A</a>

but i want only links in database 但我只想要数据库中的链接

I felt obliged to give you the DOMDocument tour: 我觉得有义务为您提供DOMDocument导览:

$d = new DOMDocument();
$d->loadHTML($result21);

$suffix = "_celebrity"; $suffix_len = strlen($suffix);

foreach ($d->getElementsByTagName('a') as $link) {
    $href = $link->getAttribute('href');
    if ($href && substr($href, -$suffix_len) === $suffix) {
        // do your insert here
    }
}

Or, using XPath instead of getElementsByTagName : 或者,使用XPath代替getElementsByTagName

$xp = new DOMXPath($d);

foreach($xp->query('//a[substring(@href, string-length(@href) - 9) = "_celebrity"]') as $node) {
    echo $node->getAttribute('href');
}

And here's a message from our chat room: 这是我们聊天室的消息:

Please, don't use mysql_* functions in new code . 请不要在新代码中使用mysql_*函数 They are no longer maintained and are officially deprecated . 它们不再维护,已正式弃用 See the red box ? 看到红色框了吗? Learn about prepared statements instead, and use PDO , or MySQLi - this article will help you decide which. 而是了解准备好的语句 ,并使用PDOMySQLi- 本文将帮助您确定哪一个。 If you choose PDO, here is a good tutorial . 如果您选择PDO, 这是一个很好的教程

You probably want to loop through $parts[1] instead of $parts[0]. 您可能想遍历$ parts [1]而不是$ parts [0]。

http://php.net/manual/en/function.preg-match-all.php http://php.net/manual/zh/function.preg-match-all.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM