简体   繁体   中英

Regex to change only one instance ofcharacter before specific string

I'm got a bunch of html code like this:

<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?

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:

$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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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