正则表达式只在特定字符串之前更改一个字符实例

时间:2010-12-27 13:15:39

标签: php html regex

我有一堆像这样的HTML代码:

<a href="http://example.com/project-a" title="Project A (test)">Project A (test</span></a>
<a href="http://example.com/project-b" title="Project B (test)">Project B (test</span></a>
<a href="http://example.com/project-c" title="Project C (test)">Project C (test</span></a>
<a href="http://example.com/project-d" title="Project D (test)">Project D (test</span></a>

你可以在每行的末尾看到它:

(test</span></a>

我想将此开场括号更改为:

<span class="example">

但是,你可以看到每一行都有其他开括号,所以我猜标准是需要更改结束范围标记之前的第一个开括号。

有没有办法用regex和php做到这一点?

2 个答案:

答案 0 :(得分:1)

好吧,如果它总是这样,你可以使用:

str_replace(' (test</span>', ' <span class="example">test</span>', $string)

或者,如果它不总是“测试”:)

preg_replace('/ \((.*?)<\/span>/', ' <span class="example">$1</span>', $string)

答案 1 :(得分:1)

使用preg_replace()功能:

$pattern = '(\*test</span></a>)';
$replaceWith = '<span class="example">';

$str = '<a href="http://example.com/project-a" title="Project A *test*">Project A *test</span></a>
<a href="http://example.com/project-b" title="Project B *test*">Project B *test</span></a>
<a href="http://example.com/project-c" title="Project C *test*">Project C *test</span></a>
<a href="http://example.com/project-d" title="Project D *test*">Project D *test</span></a>';

$newStr = preg_replace($pattern, $replaceWith, $str);