1

I want to replace the words(excluding: , ; . stc.) with links. How can I do this?

<?php
$string = "wordey; string, boom";
$string = preg_replace("/[^a-z]/i", "<a href='x'>/[^a-z]/i</a>", $string); //??
echo $string; // <a href='wordey'>wordey</a>; <a href='string'>string</a>, <a href='boom'>boom</a>
?>

Please note that the ; , . - etc are important.

4 Answers 4

2

Neither your regular expression or the replacement string make sense. The regular expression is matching everything not in the range [a-z] (denoted by the leading ^), and your replacement string appears to contain regular expression syntax, which it shouldn't.

If you're trying to replace the words, your regular expression should probably look something like /[a-z]+/i which does a case-insensitive greedy match for one or more letters.

To use the matched string in the replacement, you can use \N, where N is a number indicating the sub-match you want to reference. To add a sub-match, place brackets around the part of the regular expression you're interested in referencing. The regex becomes /([a-z]+)/i.

Put them together and you get the following, which appears to give the output you're looking for.

$string = preg_replace("/([a-z]+)/i", "<a href='\\1'>\\1</a>", $string);

Note the double-backslash is an escape sequence inserting a literal backslash into the string.

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

Comments

1
$string = preg_replace('/(\w+)/', '<a href="\\1">\\1</a>', $string);

Comments

1

try this one

http://sandbox.phpcode.eu/g/1eaa6.php

<?php 
$string = "wordey; string, boom"; 
$string = preg_replace("/(.*?)([^a-z]+)/i",  
"<a href='x'>$1</a>$2", $string);  
$string = preg_replace("/, (.*)/", ", <a href='x'>$1</a>", $string); 
echo $string; // <a href='wordey'>wordey</a>; <a href='string'>string</a>, <a href='boom'>boom</a> 
?>

Comments

1

Try this:

$result = preg_replace('/([^;,\\s]+)/', '<a href="$1">$1</a>', $subject);

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.