I need some help. I have a section that displays keywords "tags":
<?=str_replace(",",",",$line["m_tags"])?>
The code above looks like this
Tags: KEYWORD1, KEYWORD2, KEYWORD3
All I'm trying to do is have each individual KEYWORD be a hyperlink to link back to the main page.
Any help would be appreciated.
The code you posted does nothing, it replaces , with ,.
You can do this with regular expressions, but here is a different method:
$output = '';
$tmp = explode(",",$line['m_tags']); /* convert to array */
foreach($tmp as $tag)
$output .= ''.$tag.', '; /* put link in output */
echo substr($output,0,-2); /* echo output without the last , */
Shorter alternative as Felix Kling pointed out:
$tmp = explode(",",$line['m_tags']); /* convert to array */
foreach($tmp as $key => $tag)
$tmp[$key] = ''.$tag.''; /* put link back in tmp */
echo implode(",",$tmp);
Either this should work:
Tags: <?
// php5.3
$tags=explode(",", $line["m_tags"]);
$tags = array_map(function($tag){
return "<a href='http://www.yoursite.com/?tag=$tag'>$tag</a>";
}, $tags);
echo implode(", ", $tags);
?>
Here is how I would probably do it.
$str = "KEYWORD1,KEYWORD2,KEYWORD3";
$keywords = explode(',', $str);
$links = array();
foreach($keywords as $keyword) {
$links[] = "<a href='home'>$keyword</a>";
}
echo implode(', ', $links);
Related
Im finding keywords "denounce,and,demoralized" in a string, and wrapping it in "html a" tags to change it to link with following function...
function link2tags($text, $tags){
$tags = preg_replace('/\s+/', ' ', trim($tags));
$words = explode(',', $tags);
$linked = array();
foreach ( $words as $word ){
$linked[] = ''.$word.'';
}
return str_replace($words, $linked, $text);
}
echo link2tags('we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment', 'denounce,and,demoralized');
The output of the above function is as follows...
Output:
we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment
Here, the word "and" is linked 2 times I want to limit the number of links to a word
Repeat words are only linked once
You need to get only first occurrence of words and then need to replace those. Check below code:
function link2tags($text, $tags){
$tags = preg_replace('/\s+/', ' ', trim($tags));
$words = explode(',', $tags);
$linked = array();
$existingLinks = array();
foreach ( $words as $word ){
if (!in_array($word, $existingLinks)) {
$existingLinks[] = $word;
$linked[] = ''.$word.'';
}
}
foreach ($existingLinks as $key => $value) {
$text = preg_replace("/".$value."/", $linked[$key], $text, 1);
}
return $text;
}
Hope it helps you.
Here you can check existing word as below:
if(!in_array($word,$alreadyusedword)) {
$linked[] = ''.$word.'';
$alreadyusedword[] = $word;
}
In my article, I want to automatically add links to keywords.
My keywords array:
$keywords = [
0=>['id'=>1,'slug'=>'getName','url'=>'https://example.com/1'],
1=>['id'=>2,'slug'=>'testName','url'=>'https://example.com/2'],
2=>['id'=>3,'slug'=>'ign','url'=>'https://example.com/3'],
];
This is my code:
private function keywords_replace(string $string, array $key_array)
{
$array_first = $key_array;
$array_last = [];
foreach ($array_first as $key=>$value)
{
$array_last[$key] = [$key, $value['slug'], '<a target="_blank" href="' . $value['url'] . '" title="' . $value['slug'] . '">' . $value['slug'] . '</a>'];
}
$count = count($array_last);
for ($i=0; $i<$count;$i++)
{
for ($j=$count-1;$j>$i;$j--)
{
if (strlen($array_last[$j][1]) > strlen($array_last[$j-1][1]))
{
$tmp = $array_last[$j];
$array_last[$j] = $array_last[$j-1];
$array_last[$j-1] = $tmp;
}
}
}
$keys = $array_last;
foreach ($keys as $key)
{
$string = str_ireplace($key[1],$key[0],$string);
}
foreach ($keys as $key)
{
$string = str_ireplace($key[0],$key[2],$string);
}
return $string;
}
result:
$str = "<p>Just a test: getName testName";
echo $this->keywords_replace($str,$keywords);
like this:Just a test: getName testName
very import: If the string has no spaces, it will not match.Because I will use other languages, sentences will not have spaces like English. Like Wordpress key words auto link
I think my code is not perfect,Is there a better algorithm to implement this function? Thanks!
You can use array_reduce and preg_replace to replace all occurrences of the slug words in your string with the corresponding url values:
$keywords = [
0=>['id'=>1,'slug'=>'getName','url'=>'https://www.getname.com'],
1=>['id'=>2,'slug'=>'testName','url'=>'https://www.testname.com'],
2=>['id'=>3,'slug'=>'ign','url'=>'https://www.ign.com'],
];
$str = "<p>Just a test: getName testName";
echo array_reduce($keywords, function ($c, $v) { return preg_replace('/\\b(' . $v['slug'] . ')\\b/', $v['url'], $c); }, $str);
Output:
<p>Just a test: https://www.getname.com https://www.testname.com
Demo on 3v4l.org
Update
To change the text into links, you need to use this:
echo array_reduce($keywords,
function ($c, $v) {
return preg_replace('/\\b(' . $v['slug'] . ')\\b/',
'$1', $c);
},
$str);
Output:
<p>Just a test: getName testName
Updated demo
Update 2
Because some of the links that are being substituted include words that are also values of slug, it's necessary to do all the replacements at once using the array format of strtr. We build an array of patterns and replacements using array_column, array_combine and array_map, then pass that to strtr:
$reps = array_combine(array_column($keywords, 'slug'),
array_map(function ($k) { return '' . $k['slug'] . ''; }, $keywords
));
$newstr = strtr($str, $reps);
New demo
First you need to change structure of array to key/value using loop that result stored in $newKeywords. Then using preg_replace_callback() select every word in string and check that it exist in key of array. If exist, wrap it in anchor tag.
$newKeywords = [];
foreach ($keywords as $keyword)
$newKeywords[$keyword['slug']] = $keyword['url'];
$newStr = preg_replace_callback("/(\w+)/", function($m) use($newKeywords){
return isset($newKeywords[$m[0]]) ? "<a href='{$newKeywords[$m[0]]}'>{$m[0]}</a>" : $m[0];
}, $str);
Output:
<p>Just a test: <a href='https://www.getname.com'>getName</a> <a href='https://www.testname.com'>testName</a></p>
Check result in demo
My answer uses preg_replace as does Nick's above.
It relies on the patterns and replacements being equally sized arrays, with corresponding patterns and replacements.
Word boundaries need to be respected, which I doubt you can do with a simple string replacement.
<?php
$keywords = [
0=>['id'=>1,'slug'=>'foo','url'=>'https://www.example.com/foo'],
1=>['id'=>2,'slug'=>'bar','url'=>'https://www.example.com/bar'],
2=>['id'=>3,'slug'=>'baz','url'=>'https://www.example.com/baz'],
];
foreach ($keywords as $item)
{
$patterns[] = '#\b(' . $item['slug'] . ')\b#i';
$replacements[] = '$1';
}
$html = "<p>I once knew a barbed man named <i>Foo</i>, he often visited the bar.</p>";
print preg_replace($patterns, $replacements, $html);
Output:
<p>I once knew a barbed man named <i>Foo</i>, he often visited the bar.</p>
This is my answer: thanks for #Nick
$content = array_reduce($keywords , function ($c, $v) {
return preg_replace('/(>[^<>]*?)(' . $v['slug'] . ')([^<>]*?<)/', '$1$2$3', $c);
}, $str);
I need some help with twitter hashtag, I need to extract a certain hashtag as string variable in PHP.
Until now I have this
$hash = preg_replace ("/#(\\w+)/", "#$1", $tweet_text);
but this just transforms hashtag_string into link
Use preg_match() to identify the hash and capture it to a variable, like so:
$string = 'Tweet #hashtag';
preg_match("/#(\\w+)/", $string, $matches);
$hash = $matches[1];
var_dump( $hash); // Outputs 'hashtag'
Demo
I think this function will help you:
echo get_hashtags($string);
function get_hashtags($string, $str = 1) {
preg_match_all('/#(\w+)/',$string,$matches);
$i = 0;
if ($str) {
foreach ($matches[1] as $match) {
$count = count($matches[1]);
$keywords .= "$match";
$i++;
if ($count > $i) $keywords .= ", ";
}
} else {
foreach ($matches[1] as $match) {
$keyword[] = $match;
}
$keywords = $keyword;
}
return $keywords;
}
As i understand you are saying that
in text/pargraph/post you want to show tag with hash sign(#) like this:- #tag
and in url you want to remove # sign because the string after # is not sended to server in request so i have edited your code and try out this:-
$string="www.funnenjoy.com is best #SocialNetworking #website";
$text=preg_replace('/#(\\w+)/','<a href=/hash/$1>$0</a>',$string);
echo $text; // output will be www.funnenjoy.com is best <a href=search/SocialNetworking>#SocialNetworking</a> <a href=/search/website>#website</a>
Extract multiple hashtag to array
$body = 'My #name is #Eminem, I am rap #god, #Yoyoya check it #out';
$hashtag_set = [];
$array = explode('#', $body);
foreach ($array as $key => $row) {
$hashtag = [];
if (!empty($row)) {
$hashtag = explode(' ', $row);
$hashtag_set[] = '#' . $hashtag[0];
}
}
print_r($hashtag_set);
You can use preg_match_all() PHP function
preg_match_all('/(?<!\w)#\w+/', $description, $allMatches);
will give you only hastag array
preg_match_all('/#(\w+)/', $description, $allMatches);
will give you hastag and without hastag array
print_r($allMatches)
You can extract a value in a string with preg_match function
preg_match("/#(\w+)/", $tweet_text, $matches);
$hash = $matches[1];
preg_match will store matching results in an array. You should take a look at the doc to see how to play with it.
Here's a non Regex way to do it:
<?php
$tweet = "Foo bar #hashTag hello world";
$hashPos = strpos($tweet,'#');
$hashTag = '';
while ($tweet[$hashPos] !== ' ') {
$hashTag .= $tweet[$hashPos++];
}
echo $hashTag;
Demo
Note: This will only pickup the first hashtag in the tweet.
I have a PHP search script that queries a MySQL database and then parses the results through HTML to allow CSS styling. I want the script to highlight all of the keywords in the results that the user has search for. How can I do this with PHP?
My PHP script is:
<?php
mysql_connect("localhost","username","password");
mysql_select_db("database");
if(!empty($_GET['q'])){
$query=mysql_real_escape_string(trim($_GET['q']));
$searchSQL="SELECT * FROM links WHERE `title` LIKE '%{$query}%' LIMIT 8";
$searchResult=mysql_query($searchSQL);
while ($row=mysql_fetch_assoc($searchResult)){
$results[]="<a href='{$row['url']}' class='webresult'><div class='title'>{$row['title']}</div><div class='desc'>{$row['description']}</div><div class='url'>{$row['url']}</div></a>";
}
if(empty($results)){
echo 'No results were found';
} else {
echo implode($results);
}
}
?>
Simplistically you could adapt the loop here:
$searchvar = trim($_GET['q']);
while ($row=mysql_fetch_assoc($searchResult)){
$description = str_replace($searchvar, '<span class="highlight">'.$searchvar."</span>", $row['description']);
$results .="<a href='{$row['url']}' class='webresult'>
<div class='title'>{$row['title']}</div>
<div class='desc'>{$description}</div>
<div class='url'>{$row['url']}</div></a>";
}
To make it a little better:
$searchvar = explode(" ", trim($_GET['q'])); //puts each space separated word into the array.
while ($row=mysql_fetch_assoc($searchResult)){
$description = $row['description'];
foreach($searchvar as $var) $description = str_replace($var, '<span class="highlight">'.$var."</span>", $description);
$description = str_replace($searchvar, '<span class="highlight">'.$searchvar."</span>", $row['description']);
$results .="<a href='{$row['url']}' class='webresult'>
<div class='title'>{$row['title']}</div>
<div class='desc'>{$description}</div>
<div class='url'>{$row['url']}</div></a>";
}
The benefit of the second one there is that if a user types in "ipod toudch yellow" you will be searching for "ipod", "toudch" and "yellow" which would negate the type and make the results more general.
You would need to exchange the single:
like '%query%'
with
foreach(explode(" ", trim($_GET['q']) as $searchvar) $where[] = "like '%$searchvar%'";
$wheresql = implode(" OR ", $where);
to get each search "word" to be looked for in the sql or you will have a limited search with a unrelated highlight.
i also found this solution to highlight each word of the results:
$text = $searchresults;
class highlight
{
public $output_text;
function __construct($text, $words)
{
$split_words = explode( " " , $words );
foreach ($split_words as $word)
{
$text = preg_replace("|($word)|Ui" , "<b>$1</b>" , $text );
}
$this->output_text = $text;
}
}
$highlight = new highlight($searchresults, $keywords);
echo $highlight;
In case that could help,
Regards,
Max
you can use regex or simply str replace to look for a particular string and add a span around it:
while ($row=mysql_fetch_assoc($searchResult)){
$str ="<a href='".$row['url']."' class='webresult'>";
$str .="<div class='title'>".$row['title']."</div>";
$str .="<div class='desc'>";
$str .= str_replace($query,"<span class='hightlighted'>".$query."</span>",$row['description']);
$str .="</div><div class='url'>".$row['url']."</div></a>";
$result[] = $str;
}
now the css:
span.highlighted {
background-color: yellow;
}
You can use str_replace. For each keyword the user uses, put it into the $search array, and also put it into a $replace array, but surround with with a classed span tag in the latter, which you can style with CSS later. For example:
$search = array('apple', 'orange');
$replace = array();
foreach ($search as $word)
{
$replace[] = "<span class='highlight'>$word</span>";
}
$string = str_replace($search, $replace, $string);
EDIT: assuming that $query just contains keywords delimited by a single whitespace, you could get the search array this way (with explode),
$search = explode(' ', $query);
Or, if you want to add more complex logic for processing the keywords out of the $query variable (like if you use query operators like +), you could use a for loop:
$queryTerms = explode(' ', $query);
$search = array();
foreach ($queryTerms as $term)
{
// do some processing of the $term (like delete "+"?)
// ...
$search[] = $processedTerm;
}
Let's say I have the following array (which is the returned value of a database query):
Array ( [0] => PHP [1] => Webdesign [2] => Wordpress [3] => Drupal [4])
And the following string:
Working With Wordpress Shortcodes
How can I compare the array with the string to see if the string contains any word stored in the array? (hopefully that made sense to you :d )
When he finds a match (eg: Wordpress) it should create a hashtag like so:
Working With #Wordpress Shortcodes
Use preg_replace:
$tags = array('PHP', 'Webdesign', 'Wordpress', 'Drupal', 'SQL');
$text = 'Working With Wordpress Shortcodes and doing some NoSQL and SQL';
$regex = '/\b('.implode('|', array_map('preg_quote', $tags)).')\b/i';
$result = preg_replace($regex, '#$1', $text);
Would output:
Working With #Wordpress Shortcodes and doing some NoSQL and #SQL
Live example:
http://codepad.org/SxchtXmI
Loop over the array and run preg_replace over the string for each value (making sure to check for word boundaries in the regular expression (e.g. so car doesn't match cartoon)
Simply loop through your array and use strpos() (or its case-insensitive version stripos()):
$tags = array('PHP', 'Webdesign', 'Wordpress', 'Drupal');
$message = "Working With Wordpress Shortcodes";
foreach ($tags as $tag) {
$position = strpos($message, $tag);
if ($position !== false) {
// tag found! add # in front.
$message = substr($message, 0, $position).'#'.substr($message, $position);
}
}
May take much processing time (I guess) if your array is big
$hashtags = array('Wordpress', 'Twitter', 'Joomla', 'Google');
$content = "A tweet containing wordpress and joomla";
$content_breakdown = explode(' ', $content);
foreach ($hashtags as $hashtag) {
foreach ($content_breakdown as & $word) {
if (strtolower($word) == strtolower($hashtag))
$word = '#' . $word;
}
}
$content = implode($content_breakdown, ' ');
echo $content;
Output
A tweet containing #wordpress and #joomla
<?
$working_array = array('PHP','Webdesign','Wordpress','Drupal');
$string = "Working With Wordpress Shortcodes";
foreach($working_array as $array_item)
{
$the_pos = stripos($string,$array_item);
if($the_pos !== false)
{
$string = substr($string,0,$the_pos) . '#' . substr($string,$the_pos);
}
}
echo $string;
?>
Edited because I accidentally mixed some C syntax in! Sorry!
$hashtags = array('Wordpress', 'Joomla', /* ... */ );
$tweet = "This is a tweet containing Wordpress and Joomlazoom as hashtag";
$hashtags_tmp = implode('|', $hashtags);
$tweet = preg_replace("/\b($hashtags_tmp)\b/i", '#$1', $tweet);