PHP,preg_replace,用标签属性替换标签 [英] PHP, preg_replace, replace tag with tag attr

查看:53
本文介绍了PHP,preg_replace,用标签属性替换标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以详细解释一下如何使用 php 用当前属性替换标签吗?

Can I have a detail explain about how can I replace with tag with current attr using php?

我阅读了手册和一些参考资料

I read manual and some referencs

如何使用php preg_replace替换HTML标签

对于我能理解的简单命令,但是对于 preg_replace 上的搜索命令,其中包含 ~、$1、/n、 等字母,我完全不明白...

For the easy command I can understand, but for the search command on preg_replace with letters like ~, $1, /n, and etc, I dont understand at all...

如果我想替换

 <script src="core.js"></script>

进入

 <temp src="library/js/core.js"></temp>

如何实现 preg_replace?

How can I implement preg_replace?

非常感谢您的建议.

推荐答案

需要了解正则表达式,这个网站 是一个有用的资源;

You need to learn about regular expressions, this site is a useful resource;

一个带有 preg_replace 的简单例子可能是这样的 - 它可以改进,但希望能给你一个想法......

A quick example with preg_replace could be something like this - it could be improved, but hopefully will give you the idea...

<?php
$string = '<script src="core.js"></script>';
$pattern = '/<script src\s?=\s?['|"](.*)['|"]><\/script>/i';
$replace = ' <temp src="library/js/$1"></temp>';
$result = echo preg_replace($pattern, $replace, $string);
?>

您需要了解反向引用,以便使用字符串的匹配位来创建新的字符串.简而言之,您可以稍后使用包含在 $replace 字符串中的 $1 标记检索括在括号中的模式部分.您可以通过这种方式根据需要多次反向引用.您也可以在处理正则表达式时对其进行测试此处,希望对您有所帮助.

You will need to learn about back-references in order to use matched bits of the string to create your new one. Briefly, the part of your pattern that is wrapped in parenthesis can be retrieved later with the $1 token which you include in your $replace string. You can back-reference as many times as you want this way. You can test regular expressions as you are working on them here too, hope this helps.

这篇关于PHP,preg_replace,用标签属性替换标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆