0

I have a string with this value format:

$str = "Apple, Orange, Computer-Hardware, preg_replace, 50k";

or

$str = "Computer";

How can I convert it with preg_replace to:

$str = "<a href='p.php?s=Apple'>Apple</a>, <a href='p.php?s=Orange'>Orange</a>, 
<a href='p.php?s=Computer-Hardware'>Computer-Hardware</a>, <a href='p.php?s=preg_replace'>preg_replace</a>,  <a href='p.php?s=50k'>50k</a>";

$str = "<a href='p.php?s=Computer'>Computer</a>";
0

2 Answers 2

2
$str = preg_replace('/([\w-]+)/', '<a href=\'p.php?s=$1\'>$1</a>', $str);
Sign up to request clarification or add additional context in comments.

2 Comments

In the string between some words can be these two characters - , _ or numbers: ex.: preg-replcae , 56k, 50000.
@TimCoorper: in the result comma is also with the words: "<a href='p.php?s=Apple,'>Apple,</a>"
0

Have a try with:

$str = "Apple, Orange, Computer-Hardware, preg_replace, 50k";
$str = preg_replace('/([^,\s]+)/', "<a href='p.php?s=$1'>$1</a>", $str);
echo $str,"\n";

output:

<a href='p.php?s=Apple'>Apple</a>, <a href='p.php?s=Orange'>Orange</a>, <a href='p.php?s=Computer-Hardware'>Computer-Hardware</a>, <a href='p.php?s=preg_replace'>preg_replace</a>, <a href='p.php?s=50k'>50k</a>

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.