Answer the question
In order to leave comments, you need to log in
How to make the last two words a link?
Good day!
I need the last two words in a sentence to become a link. How to implement it?
Answer the question
In order to leave comments, you need to log in
Using preg_replace
<?php
$string = 'This is my habr';
$pattern = '/(\w+ \w+)$/i';
$replacement = '<a href="habr.com">${1}<a>';
echo preg_replace($pattern, $replacement, $string);
1. find the last space
2. find the penultimate space
3. split the string by the penultimate space
4. form a link from the last 2 words and your identifier
5. glue everything together
6. Profit
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question