0

I would like to replace all words starting with 3ABC with an link including the found word. For example:

teststring 3ABCJOEDKLSZ2 teststring hello test

Output would be:

test string <a href='https://google.com/search/3ABCJOEDKLSZ2'>3ABCJOEDKLSZ2</a>  teststring hello test

The substring I am looking for is always starting with 3ABC everything after that is dynamic.

3
  • 3
    Standard counter question for such kind of request: what have you tried so far? Commented Sep 13, 2018 at 13:54
  • 3
    preg_replace_callback Commented Sep 13, 2018 at 13:56
  • 3ABC\S+ or 3ABC[a-zA-Z\D]+ I think would do it... or if 3abc also is valid make the + a *. Hard to tell where your preg_replace went wrong without the code Commented Sep 13, 2018 at 13:59

2 Answers 2

2

You can use php's preg_replace function to match 3ABC followed by 0 or more characters that is not whitespace and then use the match in your code:

$literal = "teststring 3ABCJOEDKLSZ2 teststring hello test";
$formatted = preg_replace("/3ABC\S*/", '<a href="https://google.com/search/\0">\0</a>', $literal);

echo $formatted;

Fiddle: Live Demo

Sign up to request clarification or add additional context in comments.

1 Comment

As simple as it looks, I couldn't find the right replace formule. Thank you very much.
0
<?php
function makeLink($string)
{
    $pattern='/^3ABC[\w\d]+$/';
    $url='https://google.com/search/';
    $result=preg_replace($pattern, $url.$string ,$string);
    return $result;
}
echo makeLink('3ABCHJDGIFD');
?>

Like this? http://php.net/manual/en/function.preg-replace.php

the pattern will match any digit or word character after 3ABC.

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.