简体   繁体   English

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

[英]Regex to change only one instance ofcharacter before specific string

I'm got a bunch of html code like this: 我有一堆像这样的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>

You can see at the end of each line it's got: 你可以在每行的末尾看到它:

(test</span></a>

I'd like to change this opening-bracket to a: 我想把这个开口括号改为:

<span class="example">

However, you can see there are other opening-brackets on each line, so I guess the criteria is the first opening-bracket before the closing span tag needs to be changed. 但是,您可以看到每行上都有其他的开口括号,因此我想判断标准是需要更改关闭范围标记之前的第一个开口括号。

Is there a way to do this with regex and php? 有没有办法用正则表达式和PHP做到这一点?

Well, if it always looks like this, you can just use: 好吧,如果它总是这样,你可以使用:

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

Or, if it's not always "test" :) 或者,如果不总是“测试” :)

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

Use preg_replace() function: 使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM