How can I add minus - sign between spaces in tag links in PHP?

I want to put ( - ) between spaces in tag links.

	$tags = explode(",", $posts['post_tag]);
	foreach ($tags as $tag): ?>
		<?php echo "<a href='".$tag."'>".$tag."</a>"; ?>
	<?php endforeach; ?>

I do this with str_replace but the ( - ) is placed in both the tag title and the tag link. I want it to be placed in the link only

$tags = str_replace(" ", "-", $tags);

Just put the str_replace(" ", “-”, $tags) where the 1st $tag is at in the echo line -

<?php echo "<a href='".str_replace(" ", "-", $tags)."'>".$tag."</a>"; ?>
1 Like

Thank you for your reply

There is only one problem that tags without ( - ) are added to the database and therefore tags with ( - ) will not be displayed, but without ( - ) will work.
I’m adding labels with a minus sign but I don’t know if it’s correct or not
Example: tag-one, tag-two, tag-three

<?php include 'db.php'; ?>


if(isset($_GET['id']) && !empty($_GET['id'])){
    $articleTags = intval($_GET['id']);

include 'config.php'; ?>

<!doctype html>
<html lang="en">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
	a {
		text-decoration: none;

<div class="container">
	<div class="row">
		<a href="../">home<a/>

    <p>Articles in tag: <?php echo htmlspecialchars($_GET['id']);?></p>

				$articleTags = str_replace(" ", "-", $articleTags);
                $stmt = $conn->prepare('SELECT articleId, articleTitle, articleTxt, articleTags FROM techno_blog WHERE articleTags like ? ORDER BY articleId DESC');
				$stmt->bindValue(1, $articleTags);
				$posts = $stmt->fetch(PDO::FETCH_ASSOC);

<!-- Tag -->
<div class="tags-section">
	<ul class="list-inline tags">

                        $tags = explode(",", $posts['articleTags']);

                        foreach ($tags as $tag){ ?>
							<?php echo "<a href='tag/".str_replace(" ", "-", $tag)."'>".$tag."</a>"; ?>

<!-- End tag-->

				<h1 class="text-danger"><?php echo $posts['articleTitle']; ?></h1>
				<p><?php echo $posts['articleTxt']; ?></p>


    <script src="[email protected]/dist/js/bootstrap.bundle.min.js"></script>

I don’t know if this is going to make sense, but I’ll try. If the “-” is just for display purposes then simply don’t store the tags that way into the database table.

An example of what I’m talking about -

        echo '... ' on ' . CMS::styleDate($record['date_added']) .' </p>';

the date is stored diffferent in the database table and I just change the format when I output it to the screen.

Sponsor our Newsletter | Privacy Policy | Terms of Service