将某些字符转换为 HTML Link

Convert Certain Characters to HTML Link

我有这样的字符串

"hello my #old good #friends"

我想将某些词(例如 (#example))转换为 HTML 链接

"hello my <a href='example.com/tags/old'>old</a> good <a href='example.com/tags/friends'>friends</a>"   

谢谢

对不起我的英语

在 PHP 中使用 preg_match and str_replace 你可以这样做:

$someText = "hello #old things";

//Returns an array of hashtags
preg_match("/#(\w+)/", $someText, $matches);

//Generate an array of links from the hashtags
$links = [];
foreach ($matches as $hashtag)
{
    $link = "<a href=\"site.com/tag/{$hashtag}\">{$hashtag}</a>";
    array_push($links, $link);
}

//replace the arrary of hashtags in our string with the link
$string = str_replace($matches, $links, $someText);

现在可能有一种方法可以在内部进行字符串替换,但这就是我立即想到的。我会查看字符串替换并根据我的发现进行编辑。

编辑:您想在 php 还是 js 中执行此操作?

Split the string, change through it and add again.

var converted = str.split(' ').map(function(st){
    if(st.indexOf('#') !== -1){
        st = '<a href="example.com/tags/' + st.replace('#', '') + '">' + st.replace('#', '') + '</a>';
    }
    return st;
});
converted.join(' ');

var str = "hello my #old good #friends";
$('#change').on('click', function() {
  var converted = str.split(' ').map(function(st) {
    if (st.indexOf('#') !== -1) {
      st = '<a href="example.com/tags/' + st.replace('#', '') + '">' + st.replace('#', '') + '</a>';
    }
    return st;
  });
  $('#test').html(converted.join(' '));
})



//"hello my <a href='example.com/tags/old'>old</a> good <a href='example.com/tags/friends'>friends</a>"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="test">
  "hello my #old good #friends"
</div>
<button id="change">Change</button>

完全是快速回答,这可能有点过头或者不是最聪明的方法......但是这里是:

<?php

//
$string1="hey #bro this is #such a cool #answer";
$string2="hey bro this is such a cool answer";

//
print "\n String1 == ".LinkifyHashtags($string1);
print "\n String2 == ".LinkifyHashtags($string2);

//
function LinkifyHashtags($string)
{
    //
    $matches=true;

    //
    $string_linkified=$string;

    //  Grab all hashtags
    if(Preg_Match_All('@\#(?P<hash_word>\w+)@',$string,$matches)){

        //  Iterate over all matches
        foreach($matches['hash_word'] as $word){
            $word_ent=HtmlEntities($word,ENT_COMPAT,'utf-8');
            $word_enc=UrlEncode($word);
            $string_linkified=Str_Replace("#{$word}","<a href=\"/tags/{$word_enc}\">{$word_ent}</a>",$string_linkified);
        }
    }

    return $string_linkified;
}

?>

使用不带正则表达式的PHP

    $string = "hello my #old good #friends";
    $new_string=[];
    $new_string = explode(' ', $string);

    foreach ($new_string as $key => $value) {
        $space = 0 === $key ? '' : ' ';
        if ('#' === $value[0]) {
            $n_str=  str_replace("#", '', $value);
            echo "$space<a href='example.com/tags/$n_str'>$n_str</a> ";
        } else {
            echo $space . '' . $value;
        }
    }

html输出

hello my <a href='example.com/tags/old'>old</a> good <a href='example.com/tags/friends'>friends</a>

Jquery Version:

$(function(){
   var test = 'hello my #old good #friends';
   test = test.split(' ');
   test = test.map(function(item){
      return item.indexOf('#') > -1?"<a href='example.com/tags/"+item.slice(1)+"'>"+item.slice(1)+"</a>":item;
   });
   $('#divResult').html(test.join(' '));
});

工作fiddle:https://jsfiddle.net/q62htLf9/

$(document).ready(function(){
var words = 'hello my #old good #friends';
var wordarr = words.split(' ');
var str = '';
$.each(wordarr,function(i,val){
    if(wordarr[i].indexOf('#') == 0){

        wordarr[i] = '<a href="example.com/tags/'+wordarr[i].replace("#", "")+'">'+wordarr[i].replace("#", "")+'</a>';
      str += wordarr[i]+' ';  
    }else{
        str += wordarr[i]+' ';  
    }

});
$('#result').html(str);
});

https://jsfiddle.net/t8o67xuk/1/

使用php你可以像下面那样做(最简单和快速):-

使用preg_replace():-

<?php
   $data = "hello my #old good #friends";
   $patterns = array ('/#(.*?)\s/','/#(.*)$/'); // first one is start with # end with space   and second is start with # till the end
   $replace = array("<a href='example.com/tags/'></a> ","<a href='example.com/tags/'></a>");
   echo preg_replace($patterns, $replace, $data);
?>

输出:- https://eval.in/595251

使用jquery

您通过工作示例给出了很多答案。检查它们。