PHP preg_replace HTML标记

时间:2015-10-12 10:34:02

标签: php preg-replace

我需要在脚本中做一点修复,而且我在preg_replace上很糟糕。我相信对你们中的许多人来说都很容易。

我需要HTML标记内的3个特定或所有引号如下:“

所以例如: <iframe src=»http://test.test″>»hellohello»</iframe> 需要成为:<iframe src="http://test.test">»hellohello»</iframe>

到目前为止我的代码:

        $content = preg_replace("/\<[“]\>/","\"",$content); 
        $content = preg_replace("/\<[»]\>/","\"",$content); 
        $content = preg_replace("/\<[″]\>/","\"",$content); 

不起作用......

感谢您的帮助!!

3 个答案:

答案 0 :(得分:3)

你的正则表达式错误。

$content = preg_replace("/\<[“]\>/","\"",$content); 

它的意思是:

<“> 

将替换为quote。 来自其他网站的工作示例:

$content = preg_replace('/<([^<>]+)>/e', '"<" .str_replace(""", \'"\', "$1").">"', $content); 

这里使用了str_replace,你可以在那里传递任何引号。 您应该使用preg_replace_callback执行相同的操作,建议用于较新的PHP版本(不推荐使用5.5 / e标记)。 示例(不确定它的工作情况,但您明白了):

preg_replace_callback(
        '/<([^<>]+)>/',
        function ($matches) {
            return str_replace('OldQuote', 'NewQuote',$matches[0]);
        },
        $content
    );

或者使用许多不同的引号创建数组:

preg_replace_callback(
        '/<([^<>]+)>/',
        function ($matches) {
            $quotes = array('OldQuote'=>'NewQuote','OldQuote2'=>'NewQuote2');
            return str_replace(array_keys($quotes), array_values($quotes),$matches[0]);
        },
        $content
    );

答案 1 :(得分:0)

这应该可以解决问题

$content = preg_replace('/<(.+?)(?:»|“|″)(.+?)>/','<\1"\2>', $content);

一个正则表达式,匹配»之间包含<>的任何内容。 替换为\1(第一个捕获组)。接下来是“和\2(第二个捕获组)。

我希望它有所帮助

答案 2 :(得分:0)

一种解决方案是不使用preg_replace。 如果格式如您所述,您可以使用str_replace。

<html>
<head>
    <title>first ng app recieve data from database</title>
    <script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
<body ng-app="myapp" ng-controller="myctrl">
    <ul>
      <li ng-repeat="x in names">
        {{ x }}
    </li>
</ul>
<script>
    var myapp = angular.module('myapp', []);

    myapp.controller('myctrl', function ($scope, $http) {
        $http.get('ngconnect.php').success(function(data) {
            $scope.names = data;
        });

    });
</script>
</body>
</html>
相关问题