Replace contents of href attribute in php

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • testLearn
    New Member
    • Feb 2020
    • 1

    Replace contents of href attribute in php

    I have a php variable where the html contents are read as a string in php and I want to remove just the contents of the href and be the other intact.

    $string = '<a href="javascrip t:#one">String</a>';
    now I want to make this as given below.

    <a href="https://bytes.com/">String</a>. Please note that javascript#one is not constant, It is dynamic
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5388

    #2
    you might use the preg_replace method for such a task.

    Comment

    • Vanisha
      New Member
      • Jan 2023
      • 26

      #3
      To replace the contents of the href attribute in PHP, you can use string manipulation functions like str_replace or regular expressions.

      Here is an example using str_replace:
      <?php
      $link = '<a href="https://example.com">Li nk</a>';
      $new_url = 'https://newurl.com';
      $new_link = str_replace('ht tps://example.com', $new_url, $link);
      echo $new_link;
      ?>
      also do PHP online course
      In this example, the str_replace function is used to replace the old URL (https://example.com) with the new URL (https://newurl.com). The resulting string is stored in the $new_link variable and then output to the browser using echo.

      Comment

      Working...