Question

This is my first time having to do this so I have no idea how to start and no example code of what I have tried.

Basically I need to create a url path depending on the number the user types after a hashtag(#) more or less the same thing that facebook and twitter does.

For example If my url was like www.example.come/result/2657. lets say link as a comment box which you can type in comment and in this comment box you wanted to link to another page and all you have to do is hashtah follow by the numbers. e.g. "This test result is the same#2657". now if you click on'#2657'this will take you to thewww.example.come/result/2657`.

Bare in mind it will not always be 2657 also sometimes it might be www.example.come/admin/result/7485 or www.example.come/host/result/6475.

I have never done this before and I have no idea how to stand this so I don't have any example code which I have try because I have no idea how when to begin. I cant find anything on google. Please if you know, point me in the right direction.

Was it helpful?

Solution

I believe this is what you're after

Javascript Version (JQuery independent)

var str = document.getElementById("content").innerHTML;
var rx = /#\d{1,5}/g;
str = str.replace(rx, function ($0) {
    $0 = $0.split("#");
    $0 = $0[1];
    return "<a href='/my/path/to/link/" + $0 + "'>#" + $0 + "</a>";
});
document.getElementById("content").innerHTML = str;

JSfiddle Example

PHP Version

<?
function preg_callback_hash_to_link($matches) {
    return "<a href='/my/path/to/link/" . $matches[1] . "'>#" . $matches[1] . "</a>";
}

function hashtolink($html) {
    $pattern = "/(?:#)(\d{1,5})/i";
    return preg_replace_callback($pattern, 'preg_callback_hash_to_link', $html);
}

$content = "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of 'de Finibus Bonorum et Malorum' (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, 'Lorem ipsum dolor sit amet..', comes from a line in section 1.10.32. #2276 The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from 'de Finibus Bonorum et Malorum' by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham. #6578";

$content = hashtolink($content);

print $content;
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top