PHP preg_replace () change copyright year

I have the following text found in my xml a couple of times:

Copyright © 2015.

I am trying to use regex to dynamically change the above text to always reflect the current year in the final release. This is my attempt and it does not work:

$finaloutput = preg_replace("/Copyright © [0-9]+/", "test", $finaloutput); 

Of course, I use a hard-coded string ("test") only for testing purposes, because the current text already has 2015. So, my goal is to change this:

Copyright © 2015. All rights reserved ....

in it:

Copyright © test. All rights reserved....

Is my regex wrong?

PS: Just to give everyone a better understanding of the context, here (part) of the XML fragment $finaloutput is assigned:

 <div class="dict_source"><strong>Powered by</strong> <a target="_blank" rel="nofollow" href="http://www.collinsdictionary.com/dictionary/english-spanish">Collins Complete Spanish Electronic Dictionary</a><br>Copyright © 2015 HarperCollins Publishers Limited.</div> 

Update: I tried the answer suggested by @Avinash and still couldn't get it to work. To better illustrate the problem, I dug out the online tester preg_replace() . This is at https://www.functions-online.com/preg_replace.html . Here is the information that I entered in various input fields for testing:

$ pattern : '/(Copyright\s+©\s+)[0-9]+/u'

$ replacement : '\1test'

$ subject : <div class="dict_source"><strong>Powered by</strong> <a target="_blank" rel="nofollow" href="http://www.collinsdictionary.com/dictionary/english-spanish">Collins Complete Spanish Electronic Dictionary</a><br>Copyright © 2015 HarperCollins Publishers Limited.</div>

+5
source share
2 answers

Using Avinashs regex in PHP:

 <?php $subject = '<div class="dict_source"><strong>Powered by</strong> <a target="_blank" rel="nofollow" href="http://www.collinsdictionary.com/dictionary/english-spanish">Collins Complete Spanish Electronic Dictionary</a><br>Copyright © 2015 HarperCollins Publishers Limited.</div>'; $regex = '/(Copyright\s+©\s+)[0-9]+/u'; $output = preg_replace($regex, "\${1}2016", $subject); echo $output; // Happy new Year 2016! ?> 

Pay attention to the replaced part: \12016 (as they usually think) is confusing for the engine (which captured group should be used? \1 ? \12016 ? [Although this does not exist]), so the solution is to use curly braces .

+1
source

Add u modifier whenever you are dealing with Unicode characters.

 $finaloutput = preg_replace('/(Copyright\s+©\s+)[0-9]+/u', '\1test', $finaloutput); 
+6
source

Source: https://habr.com/ru/post/1238523/


All Articles