【发布时间】:2012-03-11 00:49:39
【问题描述】:
我正在尝试将我的 html 页面中的一些标题转换为 <h2>。模式很简单。
<?php
$test = "<p><strong>THIS IS A TEST</strong></p><div>And this is Random STUFF</div><p><strong>CP</strong></p>";
$pattern = "/<p><strong>([A-Z ]*?)<\/strong><\/p>/";
$replacement = "<h2>$1</h2>";
$test = preg_replace($pattern, $replacement, $test);
?>
基本上,抓取<p><strong></strong></p> 之间大写的任何内容。很简单,所以这里是复杂的部分。
首先,我需要做一个例外。 <p><strong>CP</strong></p> 不得转换为 <h2>。我尝试在<p><strong> 之后添加?!(CP),但它不起作用。
其次,我需要能够将第一个字母大写。当我在 preg_replace 上使用“ucfirst”和“strtolower”时(例如:ucfirst(strtolower(preg_replace($pattern, $replacement, $test)));),它会使字符串中的所有字符变为小写,并且 ucfirst 不起作用,因为它检测到“
任何提示,或者我是否朝着正确的方向前进?
编辑
感谢您的帮助,使用preg_replace_callback 肯定更好。我发现我所有的标题都超过 3 个字符,所以我添加了限制器。还添加了特殊字符。
这是我的最终代码:
$pattern = "/<p><strong>([A-ZÀ-ÿ0-9 ']{3,}?)<\/strong><\/p>/";
$replacement = "<h2>$1</h2>";
$test[$i] = preg_replace_callback($pattern, create_function('$matches', 'return "<h2>".ucfirst(mb_strtolower($matches[1]))."</h2>";'), $test[$i]);
【问题讨论】:
标签: php regex preg-replace lowercase negative-lookahead