How do I replace the string value in php in this case?

I’m not a PHP guy so no idea so how to do it, but tried something as given below.

Requirement:

Read More
<link href="<?php the_permalink(); ?>">

Currently gives me this output:

<link href="http://example.com/au/">

I need to change a part of URL at runtime using regular expression or any string replace function.

Something like this:

<link href="<?php echo str_replace("/au/","/uk/","<?php the_permalink(); ?>"); ?>"/>

I thought this would work, but instead it gives me this:

<link href="http://example.com/uk/"/>

Please advise what would be the correct solution.

Related posts

3 comments

  1. First, you don’t need PHP tags when you are already in PHP tags. Second the function the_permalink() doesn’t actually return the value which you want, it just displays it (See this post to see more about the difference of displaying and returing: WordPress (ACF) function does not return a value)

    So you probably want to use get_permalink() here, since this function returns the value you want. Then you can also use it almost as you already tried:

    <link href="<?php echo str_replace("/au/","/uk/", get_permalink()); ?>"/>
    
  2. Instead of manually doing a string replacement each time you need this, I recommend adding the following filter to functions.php:

    function au_to_uk_permalink($url) {
        return str_replace('/au/','/uk/', $url);
    }
    add_filter('the_permalink', 'au_to_uk_permalink');
    

    You can now use the_permalink() function as usual in your templates, and the string substitution will automatically be applied:

    <?php the_permalink(); ?>
    <!-- Outputs: http://example.com/uk/some-post/ -->
    

    Read more about the_permalink filter in the Codex.

  3. Try this:

    <?php
      $link = get_permalink();
      $link = str_replace("/au","/uk",$link);
    ?>
    <link href="<?php echo $link; ?>" />
    

Comments are closed.