【问题标题】:How to add hyperlink to a word which is a part of a string in PHP?如何将超链接添加到 PHP 中作为字符串一部分的单词?
【发布时间】:2016-01-22 12:40:34
【问题描述】:

我有一个字符串和一个链接,如下:

$link = 'https://www.google.co.in';
$str = 'Hi all welcome to the google page Google Page';

现在我想让'Google Page'这个词成为一个超链接。当整个字符串 ($str) 将出现在网页上时,字符串 'Google Page' 应显示为超链接,单击它时链接 'https://www.google.co.in' 应打开。

为了实现这一点,我尝试了以下代码但没有成功。

Phpfox::getUserBy('full_name').' accepted your request to join'.<a href=$sLink>Google Page</a>Group Name
echo 'Hi all welcome to the google page <a href=$link> '.Google Page'.'</a>'';

有人可以帮助我并纠正我在代码中所犯的错误吗?

谢谢。

【问题讨论】:

    标签: php string hyperlink anchor string-concatenation


    【解决方案1】:

    你的字符串用单引号括起来。当你单引号你的字符串时,你告诉 PHP 显示字符串 as-is。因此,$link 变量将不会被解释。

    MuthaFury's solution 的替代方法是将单引号更改为双引号,以告诉 php 您确实希望解释 $link 变量。

    echo "Hi all welcome to the google page <a href=\"$link\">Google Page</a>";
    

    【讨论】:

      【解决方案2】:

      试试这个

      echo 'Hi all welcome to the google page <a href="'.$link.'">Google Page</a>';
      

      【讨论】:

        【解决方案3】:
        $link = 'https://www.google.co.in';
        $str = 'Hi all welcome to the google page Google Page and another Google Page just for test';
        $word = 'Google Page';
        echo str_replace($word, "<a href=\"{$link}\">{$word}</a>", $str);
        

        【讨论】:

        • 好主意,虽然如果文本中还有Google PagesGoogle Pagerank 等可能效果不佳。
        猜你喜欢
        • 2013-12-11
        • 2018-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多