I know the title sounds like an easy thing to do. But its not. I want to check that my user's message has 2 -'s in it. Then replace the first - with <s> then the second one with </s> and i dont know how to check for to dashe's but this is what i have to change it

<?php
$ID = $_COOKIE['idCookie'];
$memberid = $_GET['id'];
$query = mysql_query("SELECT * FROM `private_messages` WHERE to_id='$ID' AND To_Deleted='0' AND from_id='$memberid' OR to_id='$memberid' AND from_id='$ID'");
while($row = mysql_fetch_assoc($query)){
    $subject = $row['subject'];
    $toid = $row['to_id'];
    $read = $row['opened'];
    $fromid = $row['from_id'];
    $message = $row['message'];
    $message = str_replace($smile_symble, $smile_pic, $message);
    $strike = array("-","-"); //probably dont need 2 do i?
    $strike1 = array("<s>","</s>");
    $message = str_replace($strike, $strike1, $message)
?>

Dani AI

Generated

— don’t use plain str_replace for this. It can’t do “first hyphen = open tag, second hyphen = close tag” reliably and will also mis-handle multiple pairs or hyphens inside words. is on the right track with a regex, but you want a non‑greedy match and to escape the inner text to avoid HTML/XSS problems.

// only do the conversion if there are at least two hyphens
if (substr_count($message, '-') >= 2) {
    $message = preg_replace_callback(
        '/-(.+?)-/s',
        function ($m) {
            return '<s>' . htmlspecialchars($m[1], ENT_QUOTES, 'UTF-8') . '</s>';
        },
        $message,
        1  // change to -1 or omit to replace all pairs, use 1 to only replace the first pair
    );
}

If you want to avoid converting hyphens that are inside words (e.g. co-op) use a pattern that preserves surrounding whitespace and re-inserts it:

$message = preg_replace_callback(
    '/(^|\s)-(.+?)-(\s|$)/su',
    function ($m) {
        return $m[1] . '<s>' . htmlspecialchars($m[2], ENT_QUOTES, 'UTF-8') . '</s>' . $m[3];
    },
    $message
);

Troubleshooting notes: include the s modifier so . matches newlines and u for UTF‑8 if needed. Decide whether to replace only the first pair (use the limit param) or every pair. Sanitize user input properly — either strip/clean tags when you save, or use a sanitizer (HTMLPurifier or similar) and then safely allow <s> when rendering. Test edge cases: nested hyphens, ranges (e.g. 1-10), multiline content, and previously-escaped text to avoid double-escaping.

Member Avatar for Member #951872
<?php

$sample_text = 'Things between hyphens will be -striked out-';

$new_text = preg_replace('/\-(.*)\-/', '<s>$1</s>', $sample_text);

echo $new_text;

?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.