A
A
alex_litv2021-08-10 18:11:43
PHP
alex_litv, 2021-08-10 18:11:43

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

2 answer(s)
S
Slava Rozhnev, 2021-08-10
@alex_litv

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

Test PHP preg_replace here

V
Vladimir Korotenko, 2021-08-10
@firedragon

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 question

Ask a Question

731 491 924 answers to any question