将尚无超链接的文本替换为超链接

2024-03-07

一个更好的例子是这样的:

$string = "That is a very nice ford mustang, if only every other ford was quite as nice as this honda";

我想用制造商和型号的链接替换汽车名称(如果它们匹配),或者只是制造商,但如果有品牌和型号,如果您使用 str 替换,它会将链接放在链接中......

$remove = array("ford mustang","ford","honda");
$replaceWith = array("<a href='fordID'>ford</a>","<a href='fordmustangID'>ford mustang</a>","<a href='hondaID'>honda</a>");

这给出了结果:

"That is a very nice <a href='<a href='fordmustangID'>ford mustang</a>ID'><a href='fordmustangID'>ford mustang</a></a>, if only every other <a href='fordmustangID'>ford mustang</a> was quite as nice as this <a href='hondaID'>honda</a>"

我只希望它创建一个超链接(如果还没有这样的超链接):

  "That is a very nice <a href='fordmustangID'>ford mustang</a>, if only every other <a href='fordID'>ford</a> was quite as nice as this <a href='hondaID'>honda</a>"

edit:

我花了很长时间,但这是我想到的:

function replaceLinks($replacements, $string){
    foreach($replacements as $key=>$val){
        $key=strtolower((string)$key);
        $newReplacements[$key]=array();
        $newReplacements[$key]['id']=$val;
        //strings to make sure the search isn't in front of
        $newReplacements[$key]['behinds']=array();
        //strings to make sure the search isn't behind
        $newReplacements[$key]['aheads']=array();
        //check for other searches this is a substring of
        foreach($replacements as $key2=>$val2){
            $key2=(string)$key2;
            /* 
            //debugging
            $b = ($key=='11 22'&&$key2=='11 22 33');
            if($b){
                l('strlen $key2: '.strlen($key2));
                l('strlen $key: '.strlen($key));
                l('strpos: '.(strpos($key2,$key)));

            }
            */
            //the second search is longer and the first is a substring of it
            if(strlen($key2)>strlen($key) && ($pos=strpos($key2,$key))!==false){
                //the first search isn't at the start of the second search ('the ford' and 'ford')
                if($pos!=0){
                    $newReplacements[$key]['behinds'][]=substr($key2,0,$pos);
                }
                //it's not at the end ('ford' and 'fords')
                if(($end=$pos+strlen($key))!=strlen($key2)){
                    $newReplacements[$key]['aheads'][]=substr($key2,$end);
                }
            }
        }
    }
    foreach($newReplacements as $key=>$item){
        //negative lookbehind for words or >
        $tmp="/(?<![\w>=])";
        //negative lookbehinds for the beginnings of other searches that this search is a subtring of
        foreach($item['behinds'] as $b){
            $tmp.="(?<!$b)";
        }
        //the actual search
        $tmp.="($key)";
        //negative lookaheads for ends of other searches that this is a substring of.
        foreach($item['aheads'] as $a){
            $tmp.="(?!$a)";
        }
        //case insensitive
        $tmp.='/ie';
        $replacementMatches[]=$tmp;
    }
    return preg_replace($replacementMatches,'"<a href=\"".$newReplacements[strtolower("$1")]["id"]."\">$1</a>"' ,$string);

}

向其传递一个数组,例如您正在讨论的数组:

$replaceWith = array('ford mustang'=>123,'ford'=>42,'honda'=>324);

和一个字符串:

$string = "That is a very nice ford mustang, if only every other ford was quite as nice as this honda";

echo replaceLinks($replaceWith,$string);

它优先考虑较大的字符串键,因此如果您有ford and ford mustang,它将取代ford mustang与链接。




Not very practical, but might work.

$string = "That is a very nice ford mustang, if only every other ford was quite as nice as this honda";
$remove = array("/(?<![\w>])ford mustang(?![\w<])/",'/(?<![>\w])ford(?! mustang)(?![<\w])/',"/(?<![>\w])honda(?![<\w])/");
$replaceWith = array("<a href='fordmustangID'>ford mustang</a>","<a href='fordID'>ford</a>","<a href='hondaID'>honda</a>");
echo preg_replace($remove, $replaceWith,$string);

我使用带有负向前查找和向后查找的正则表达式来确保我们要替换的字符串部分不是字母数字序列的一部分(例如12ford23 or afford) 或触摸元素的开始或结束标记。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将尚无超链接的文本替换为超链接 的相关文章

  • 使用 PHP 正则表达式从字符串中提取年份[重复]

    这个问题在这里已经有答案了 我想从字符串中提取年份 我得到了一个不完整的解决方案 我的字符串总是这样 请将爵士乐 2014 和 2015 的 mpg 发送至我的手机号码 123456789 我尝试过以下正则表达式 preg match al
  • PayPal Rest API for Payments 在沙箱中返回 NULL

    我有一个 PayPal 沙盒帐户 我可以在 PHP 上使用curl 通过 api 检索令牌 但是处理测试卡只会返回 null 有人看到代码有问题吗 这是 PayPal 沙盒的已知问题吗 下面代码片段中的客户端是伪造的 但是 如前所述 使用我
  • 在composer.json中运行命令行命令

    我正在尝试编写一个composer json 文件 该文件将连续运行多个命令行命令 作为一个示例 如下所示 scripts test createDir createDir mkdir testing 当我在终端中运行作曲家文件时使用com
  • PHP:__toString() 和 json_encode() 不能很好地协同工作

    我遇到了一个奇怪的问题 我不知道如何解决它 我有几个类 它们都是 JSON 对象的 PHP 实现 这是问题的说明 class A protected a public function construct this gt a array n
  • 在 WooCommerce 订单和电子邮件中添加并显示自定义购物车项目数据

    我有一个名为彩票的自定义 woocommerce 产品类型 我需要在其上添加一个自定义选择字段 因为它不是可变产品 所以我添加了一个 一切工作正常 我在购物车和结帐中也获得了价值 但我无法在管理订单或订单邮件 客户和管理员 中获得价值 这是
  • 如何在 laravel/php 中访问该集合的内容

    我是 Laravel 的新手 正在做一个构建迷你社交网络应用程序的项目 我有一个与用户模型有关系的帖子模型 我有一个帖子页面 其中仅显示经过身份验证的用户及其朋友的帖子 在我的 PostController 中 我像这样查询经过身份验证的用
  • Laravel 5 Eloquent 关系:无法修改/覆盖关系表属性

    我正在使用 Laravel 5belongsToMany使用中间数据透视表定义相关表的方法 我的应用程序正在使用雄辩的模型Tour and 旅游类别 在游览模型中我有 namespace App use Illuminate Databas
  • CodeIgniter Active Record - 组 OR 语句

    这是我的问题 MySQL 或 条件 https stackoverflow com questions 8604380 mysql or condition 解决方案是将 OR 语句分组 但我正在使用 CodeIgniters Active
  • 将 PHP 变量保存到文本文件

    我想知道如何将 PHP 变量保存到 txt 文件 然后 再次检索它们 Example 有一个输入框 提交后写的东西 输入框将被保存到文本文件中 稍后需要结果 作为变量带回 假设变量是 text I 需要将其保存到文本文件并能够将其检索回来
  • 如何在 phpfarm php 安装上安装 pthreads

    记录我为帮助他人所做的努力 并希望得到一些关于我如何做得更好的反馈 命令pecl install pthreads由于我的 php 安装失败ubuntu 13 04盒子没有配置 zts Options 1 ubuntu存储库没有启用zts的
  • 电话号码的正则表达式,不允许全零

    需要您的正则表达式帮助 我当前的正则表达式是 d 8 最小长度为 8 不允许包含字母 特殊字符和空格 我还想禁止全零 如 00000000 Thanks 该模式应该可以满足您的需求 0 d 8 The 0 部分是负前瞻 将阻止仅输入零 Ex
  • PHP 使用 use 关键字导入类

    到目前为止我还没有使用PHPuse词 但现在必须 索引 php内容 require once Classes MainClass php obj new Main echo obj gt test 类 MainClass php
  • 如何使用 PHP SoapClient 添加任意命名空间?

    如何使用 PHP SoapClient 添加任意名称空间 命名空间实际上并未在请求中使用 但我认为它阻止了我的消息被正确使用 WSDL 在这里 http abr business gov au abrxmlsearchRPC ABRXMLS
  • 如何设置外键id的id #sf2 #doctrine2

    我正在尝试手动为对象设置外键 id 但没有找到如何执行此操作 class Item ORM ManyToOne targetEntity MyBundle Entity ItemType inversedBy itemTypes ORM J
  • 即使 is_dir 是一个目录,它也会返回 false 吗?

    为什么 is dir 即使是一个目录也会返回 false 没有返回错误 path mysql var lib mysql if is dir path mysql echo error 返回错误 path mysql var lib mys
  • 尝试使用curl进行GET,发送的值允许为空

    我正在尝试使用curl 来执行一个简单的GET 其中包含一个名为redirect uri 的参数 被调用的 php 文件打印出 GET redirect uri 的空字符串 它显示 red 并且似乎没有发送任何内容 执行获取操作的代码 Ge
  • Curl 和 Php 5.3.3 中的 SSL 连接错误

    我的网站自 3 年来一直运行良好 代码如下 现在突然从 2 天开始出现以下错误 SSL 连接错误 在 Curl error 中 下面是我的代码
  • CKEditor TypeError:c[a] 在 CodeIgniter 中未定义

    我正在尝试在基于 codeigniter 的网站中安装 CKEditor 并且我已按照本教程进行操作 Codeigniter 教程中的 CKEditor http nukium com developpement php framework
  • SQL查询:按字符长度排序?

    是否可以按字符总数对sql数据行进行排序 e g SELECT FROM database ORDER BY data length 我想你想用这个 http dev mysql com doc refman 5 0 en string f
  • 在 Laravel 视图中使用 CSS?

    我刚刚开始学习 Laravel 并且可以掌握控制器和路由的基础知识 我的操作系统是 Mac OS X Lion 它位于 MAMP 服务器上 我的routes php代码 Route get function return View make

随机推荐