Spaces are invalid characters in URLs. Your links are broken, whether the posts exist or not and regardless of whether you want the spaces or not.
And uppercase/lowercase can get you in trouble too. Some servers are case sensitive so if you have a permalink to http://somesite.com/hello-world
a link like http://somesite.com/Hello-World
might work or it might not. You don’t want pages to 404 over case, right?
Your code is out of content so it hard to test but …
$content = "(link: http://example.com/test )"; // assuming links like this
$post="Abc Def"; // and assuming $post is the post title
$content = preg_replace(
'%\(link: ?(.*?) ?\)%',
'(link: <a href="http://somesite.com/'.sanitize_title_with_dashes($post).'" title="'.$post.'">'.$post.'</a>)',
$content
);
There are a couple of things I noticed about your code.
$post
is a global variable used by WordPress. You appear to
clobbering it by setting it to the post title instead of leaving it
as the post Object as it should be. I would recommend using a
different variable name.- In PHP, variables do not expand inside single quotes so the parts of
your code where you had variables inside single quotes would not
have printed the way you wanted. For example,
title="$post">$post</a>)'
would have literally been
title="$post">$post</a>)'
On further thought, rather than convert the title to the permalink the way you are trying to do you’d be better off just using $post->post_name
, with $post
being the post Object it should be. WordPress initially converts the title to the permalink the way that I did, but the title can be edited independently of the permalink. There is no guarantee that converting the title will work.
As it turns out the real question is how to capture and convert the user supplied input. For that you need preg_replace_callback
.
function transform_pseudo_anchor_wpse_101201($match) {
if (isset($match[1])) {
return '(link: <a href="http://example.com/'.sanitize_title_with_dashes($match[1]).'" title="'.$match[1].'">'.$match[1].'</a>)';
}
}
$content = preg_replace_callback(
'%\(link: ?(.*?) ?\)%',
'transform_pseudo_anchor_wpse_101201',
$content
);
echo $content;