user2001487
user2001487

Reputation: 463

preg_match multiple search replace in string

I'm trying to perform a multiple search and replace in a string given a list of prefixes.

For example:

$string = "CHG000000135733, CHG000000135822, CHG000000135823";
if (preg_match('/((CHG|INC|HD|TSK)0+)(\d+)/', $string, $id)) {
# $id[0] - CHG.*
# $id[1] - CHG(0+)
# $id[2] - CHG
# $id[3] - \d+ # excludes zeros

$newline = preg_replace("/($id[3])/","<a href=\"http://www.url.com/newline.php?id=".$id[0]."\">\\1</a>", $string);
}

This only changes CHG000000135733. How can I make the code work to replace the other two CHG numbers as links to their corresponding numbers.

SOLVED using this piece of code submitted by Casimir et Hippolyte.

$newline = preg_replace ('~(?:CHG|INC|HD|TSK)0++(\d++)~', '<a href="http://www.url.com/newline.php?id=$0">$0</a>', $string);

Upvotes: 2

Views: 388

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89567

No need to use preg_match before. In one line:

$newline = preg_replace ('~(?:CHG|INC|HD|TSK)0++(\d++)~', '<a href="http://www.url.com/newline.php?id=$0">$1</a>', $string);

Upvotes: 1

Dinesh
Dinesh

Reputation: 3105

you will need to iterate over them:

$string = "CHG000000135733, CHG000000135822, CHG000000135823";
$stringArr = explode(" ", $string);
$newLine = "";
foreach($stringArr as $str)
{
    if (preg_match('/((CHG|INC|HD|TSK)0+)(\d+)/', $str, $id)) {
    # $id[0] - CHG.*
    # $id[1] - CHG(0+)
    # $id[2] - CHG
    # $id[3] - \d+ # excludes zeros

    $newline .= preg_replace("/($id[3])/","<a href=\"http://www.url.com/newline.php?id=".$id[0]."\">\\1</a>", $str);
}

your new line variable will have all three urls appended to it as shown but you can modify it do watever you want with the urls..

Upvotes: 0

Related Questions