Home > database >  Replace multiple strings that start with # in a text with a link
Replace multiple strings that start with # in a text with a link

Time:08-10

I have a long text and within the text, there are numbers that start with #, for example, #23, #8, #123. Each number represents a link. I need to change those numbers with the link. For example, remove #23 with mywebsite.com and #8 with anotherwebsite.com

CodePudding user response:

Based on your comments, I'm going to assume you essentially want to replace all instances of numbers like #12 with a URL that's stored somewhere (database or statically in a variable).

There's a few ways you can do this. I'd suggest either using a regular expression or a direct replacement. If you use a direct replacement, make sure you process each match in "most specific" first (so that #12 doesn't get replaced by #1 first).

This example makes a few assumptions but hopefully you can work it into your project.

// declare replacement map
// this could be created from database records
// in that case, you would convert into this key/value structure
$url_map = [
    "1" => "somewebsite.com",
    "2" => "anotherone.com",
    "23" => "google.com",
];

// this could be a value returned from the database
$text = "Some example text (#1) to replace all references #2 with links: #23";

// now we want to replace all matches with their relevant URL
// PREG_OFFSET_CAPTURE is important here so that we know
// where in the text to insert the replacement
preg_match_all("/#\d /", $text, $matches, PREG_OFFSET_CAPTURE);

// Simplify and reverse.
// We select the first item [0] as we have no capturing groups.
// We reverse so that we can ensure each matched index stays the same.
// If we didn't reverse, we would need to loop, replacing 1 match each
// iteration
$matches = array_reverse($matches[0]);

// process each match
foreach ($matches as $match) {
    $hash = $match[0]; // e.g. #23
    $index = $match[1]; // e.g. 64

    $key = substr($hash, 1); // get number without hash -> e.g. 23
    $url = $url_map[$key];

    $text = substr_replace($text, $url, $index, strlen($hash));
}

echo $text;
// outputs::
// "Some example text (somewebsite.com) to replace all references anotherone.com with links: google.com"

Link to documentation:

  • Related