I have the following text occurring in my xml a couple of times:
Copyright © 2015.
I am trying to use regex to change the above text dynamically so as to always reflect the current year in the final output. This is my attempt and it doesn't seem to work:
$finaloutput = preg_replace("/Copyright © [0-9]+/", "test", $finaloutput);
Of course, I am using a hard-coded string ("test") just for testing purposes because the current text already has 2015 in it. So, my goal here is to change this:
Copyright © 2015. All rights reserved....
into this:
Copyright © test. All rights reserved....
Is my regex wrong?
P.S.: Just for the sake of giving everyone a better feel of the context, here's (a portion of) the XML snippet $finaloutput
is assigned to:
<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 offered by @Avinash and still failed to make it work. In order to illustrate the issue better, I have dug out an online preg_replace()
tester. It's over at https://www.functions-online.com/preg_replace.html. Here's the information I entered in the 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>
Add u
modifier whenever you're dealing with unicode characters.
$finaloutput = preg_replace('/(Copyright\s+©\s+)[0-9]+/u', '\1test', $finaloutput);
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!
?>
Mind the replacement part: \12016
(as one would normally think) is confusing for the engine (which captured group shall be used? \1
? \12016
? [though this does not exist]), so the solution is to use curly brackets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With