【问题标题】:jquery find http elements in plain text and convert it to a linkjquery以纯文本查找http元素并将其转换为链接
【发布时间】:2012-12-27 11:07:09
【问题描述】:

我不知道这是否可行,但我有一段纯文本,其中始终包括:

http://www.royalmail/portal/etc/etc/track.php?trackNumber=123345323

当从数据库拖到我的页面时,这显然不会呈现为链接。有什么方法可以选择这段文本(即通过http://)并在最基本的情况下用锚标签包装它 - 或者更复杂的是 - 检索地址,用锚标签包装地址,并更改原始@987654323 @文本到更易于理解的内容,例如“跟踪包裹”

需要注意的是,可能会同时循环出多个跟踪引用。

我的包含HTML如下

<div class="message_holder">
                <div class="mess_head" style="width:110px;">
                    <p><strong>Sender: </strong><? echo $row11['sender'];?></p>
                </div>
                <div class="mess_head" style="width:450px;">
                    <p><strong>Subject: </strong><span class="red"><? echo $row11['subject'];?></span></p>
                </div>
                <div class="mess_head" style="width:150px;">
                    <p><strong>Date Sent: </strong><? echo date('d/m/Y, H.ia', $row11['date_sent']);?></p>
                </div>
                <div class="mess_head" style="width:200px;">
                    <p><strong>Message ID: </strong><? echo $row11['message_id'];?></p>
                </div>
                <div class="mess_body">
                    <p><? echo html_entity_decode($row11['message']);?></p>
                </div>
            </div>

纯文本链接将全部显示在“mess_body”类中。我试过使用html_entity_decode(),但这并没有成功。如果有一种简单的方法可以通过 PHP 而不是 JQuery 做到这一点,它可能会更简单。

【问题讨论】:

  • 您应该使用 PHP 而不是 Javascript 来执行此操作。为什么你不能只做&lt;a href="&lt;? echo html_entity_decode($row11['message']);?&gt;"&gt;Track Parcel&lt;/a&gt;
  • 链接引用包含在其他纯文本中,因此需要将其标识为链接。

标签: php jquery jquery-selectors


【解决方案1】:

我会用 PHP 来做:

$text = preg_replace(
    '@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', 
    '<a href="$1">$1</a>', /* or <a href="$1">Your TEXT</a> */
    $text
);

如果我猜对了,url 可以在你的消息中,所以你的代码应该是这样的:

<?php 
    echo 
     preg_replace(
        '@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@smi', 
        '<a href="$1">$1</a>',
        html_entity_decode($row11['message'])
     );
 ?>

【讨论】:

  • 这使得它比使用我的 jquery 想法更简单,但我似乎无法让你的示例在我的代码中工作 - 会继续搞砸这个 - 谢谢
  • @Sideshow 为您的代码添加了一个示例。您是否遇到任何类型的错误,或者您能否提供可用作测试用例的示例消息?
  • 脚本运行良好 - 示例消息如下:Tracking Number: BY281883295GB 以上 Royal Mail Tracking Number 已分配给 Appointment ID: 1357901511AeA 跟踪号可能需要几个小时才能变为住在皇家邮政网站上。请点击以下链接了解跟踪详情:track2.royalmail.com/portal/rm/track?trackNumber=11111111111
猜你喜欢
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
  • 2013-01-15
  • 1970-01-01
  • 2014-04-07
  • 2016-04-04
  • 2023-03-11
  • 2023-04-10
相关资源
最近更新 更多