douli7841 2011-08-04 18:36
浏览 46
已采纳

too long

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条回答 默认 最新

  • duanbei6427 2011-08-04 18:41
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程