2

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);
1
  • what's in $input? You never define it. Commented Apr 29, 2013 at 0:01

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.