I create this pattern
$pattern = "/<a href='(?<href>.+?)'>(?<name>.+?)<\/a>/i";
And i have this example,
$string = "<a href='https://www.php.net/'>https://www.php.net/</a>
<a href='https://stackoverflow.com/'>https://stackoverflow.com/</a>
<a href='https://www.google.com/'>https://www.google.com/</a>";
Using this, i can find the matches and extract the href, and the name.
preg_match_all($pattern, $string, $matches);
Array
(
[0] => Array
(
[0] => https://www.php.net/
[1] => https://stackoverflow.com/
[2] => https://www.google.com/
)
[href] => Array
(
[0] => https://www.php.net/
[1] => https://stackoverflow.com/
[2] => https://www.google.com/
)
[1] => Array
(
[0] => https://www.php.net/
[1] => https://stackoverflow.com/
[2] => https://www.google.com/
)
[name] => Array
(
[0] => https://www.php.net/
[1] => https://stackoverflow.com/
[2] => https://www.google.com/
)
[2] => Array
(
[0] => https://www.php.net/
[1] => https://stackoverflow.com/
[2] => https://www.google.com/
)
)
The problem is when I use the preg_replace, since the pattern is the same, it changes the same information for all the URL, and i need to change only the name and preserve the rest of the information accordingly.
Using,
if(preg_match_all($pattern, $string, $matches))
{
$string = preg_replace($pattern, "<a href='$1'>Name</a>", $string);
}
I can get the results from the groups, and preserve the first part of the href. But if i try to change the name, it's the same for all results.
If I try to use "str_replace", I can have different results as intended, but this gave me 2 problems. One is that if i try to replace the name, i also change the href, and if i have similar URL with "more slashes" it will change the match part, and leave the rest of the information.
In a database I have list of URL with a column that have names, and if the string match any row in the table I need to change the name accordingly and preserve the href.
Any help?
Thank you.
Kind regards!