开发者

How to fix this string replace php problem?

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&开发者_开发技巧lt;/a>
?>

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


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.


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


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


Try this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜