bestprogrammerintheworld
bestprogrammerintheworld

Reputation: 5520

Replace string only inside of a link

I have a string like this:

<a href="blabla/test/city">city</a>

I want to delete only the last occurence of /city in the actual link and I will have this:

<a href="blabla/test">city</a>

I can’t just do a replace cause I don’t want to replace the city that shows in browser.

I’ve started doing something:

$x = '<a href="test/gothenburg">gothenburg</a>';    
$pos = strrpos($x, '">');
$x = substr($x, 0, $pos);                        
echo $x;

How do I achieve this replacement safely?

Upvotes: 1

Views: 61

Answers (4)

Giacomo1968
Giacomo1968

Reputation: 26066

Came up with a solution using preg_match and preg_replace that will look for the city name between the <a href="…"></a> tags, and then find the href and remove the last part of the URL that contains the city name:

// Set the city link HTML.
$city_link_html = '<a href="test/gothenburg/">gothenburg</a>';

// Run a regex to get the value between the link tags.
preg_match('/(?<=>).*?(?=<\/a>)/is', $city_link_html, $city_matches);

// Run the preg match all command with the regex pattern.
preg_match('/(?<=href=")[^\s"]+/is', $city_link_html, $city_url_matches);

// Set the new city URL by removing only the the matched city from the URL.
$new_city_url = preg_replace('#' . $city_matches[0] . '?/$#', '', $city_url_matches[0]);

// Replace the old city URL in the string with the new city URL.
$city_link_html = preg_replace('#' . $city_url_matches[0] . '#', $new_city_url, $city_link_html);

// Echo the results with 'htmlentities' so the results can be read in a browser.
echo htmlentities($city_link_html);

And the end result is:

<a href="test/">gothenburg</a>

Upvotes: 0

l&#39;L&#39;l
l&#39;L&#39;l

Reputation: 47169

You could use preg_replace:

$searchText = '<a href="blabla/test/city">city</a>';

$result = preg_replace("/(\/\w+)(?=[\"])/u", "", $searchText);

print_r($result);

output:

<a href="blabla/test">city</a>

example:

http://regex101.com/r/gZ7aG9

To leave the / before the replaced word you can use pattern: (\w+)(?=["])

Upvotes: 1

user3712744
user3712744

Reputation: 1

strreplace(Href="blabla/test/city", href="blabla/test")

use the real str replace ofcourse

Upvotes: 0

Charles
Charles

Reputation: 437

<?php
$x = '<a href="test/gothenburg">gothenburg</a>';  
$pattern = '/\w+">/'; 
$y = preg_replace($pattern, '">', $x);
echo $y;

?>

Upvotes: 0

Related Questions