Okay suppose we would like to get title,keywords and description of website so i'm going to use the following function
<?PHP
function getInfo($URL)
{
$getInfo= get_meta_tags($URL);
return $getInfo;
}
$URL = "http://www.my_site.com"; // URL
// Applying the function
$_getInfo = getInfo($URL);
// Print the results.
echo $_getInfo ["keywords"]."<br>"; // gives keywords
echo $_getInfo ["description"]."<br>"; // gives description
?>
Yet,everything if fine but suppose the results as following
Keywords
php,profitable,share
Description
Advanced profitable and featured script to share
As in this example we've some keywords found in description profitable and share
The question is how to highlight keywords that only found in description!!
I will add the following css
<style>
.highlight{background: #CEDAEB;}
.highlight_important{background: #F8DCB8;}
</style>
and will add this function to alter between two different colors just like in css code
<?PHP
function hightlight($str, $keywords = '')
{
$keywords = preg_replace('/\s\s+/', ' ', strip_tags(trim($keywords))); // filter
$style = 'highlight';
$style_i = 'highlight_important';
$var = '';
foreach (explode(' ', $keywords) as $keyword) {
$replacement = "<span class='".$style."'>".$keyword."</span>";
$var .= $replacement." ";
$str = str_ireplace($keyword, $replacement, $str);
}
$str = str_ireplace(rtrim($var), "<span class='".$style_i."'>".$keywords."</span>", $str);
return $str;
}
?>
Now applying both (Not working)
$string = hightlight($_getInfo["description"], $_getInfo ["keywords"]);
echo $string;
Why not working cause it define $_getInfo ["keywords"] as one word php,profitable,share
which indeed not found in description in that shape.
so how can i apply it by using explode or foreach (i guess) so the out put be like this :
I wonder if there was another way to do it if mine looks not good way. ~ Thanks
Since your keywords are in list format you need to:
foreach(explode(',', $keywords) as $keyword)
Related
I'm using PHP to filter my title to remove the word "Tag:" inside and it is working fine, however when my following word starts with "T" it will instantly be removed as well.
This was how i've set my code
<?php $tag = "Tag: ";
if( str_replace( $tag, "", $title) == true ):
else:echo ltrim($title, $tag);
endif ?>
so when my title is Tag: Home it will return Home just fine,
but if my title is something like Tag: Teachers it will return me eachers instead.
How do i make it so I can still display any title starting with T without it being removed.
Try this. it will returns only Teacher
$str = "Tag: Teacher";
$str = str_replace("Tag:", "", $str);
echo $str;
Use following to remove the tag Tag:
<?php
$title = 'Tag: Teachers';
echo removeTag($title); // Teachers
function removeTag(string $str, string $tag = "Tag: "): string
{
$str = str_replace($tag, "", $str);
return $str;
}
I have a link being outputted on my site, what i want to do is replace the visible text that the user sees, but the link will always remain the same.
There will be many different dynamic urls with the text being changed, so all the example regex that i have found so far only use exact tags like '/.*/'...or something similar
Edited for a better example
$link = '<a href='some-dynamic-link'>Text to replace</a>';
$pattern = '/#(<a.*?>).*?(</a>)#/';
$new_text = 'New text';
$new_link = preg_replace($pattern, $new_text, $link);
When printing the output, the following is what i am looking for, against my result.
Desired
<a href='some-dynamic-link'>New text</a>
Actual
'New text'
As you're already using the capture groups, why not actually use them.
$link = "<a href='some-dynamic-link'>Text to replace</a>";
$newText = "Replaced!";
$result = preg_replace('/(<a.*?>).*?(<\/a>)/', '$1'.$newText.'$2', $link);
If you needs to get everything in Between tags then you can use below function
<?php
function getEverything_inBetween_tags(string $htmlStr, string $tagname)
{
$pattern = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
preg_match_all($pattern, $htmlStr, $matches);
return $matches[1];
}
$str = 'see here for more details about test.com';
echo getEverything_inBetween_tags($str, 'a');
//output:- see here for more details about test.com
?>
if you needs to extract HTML Tag & get Array of that tag
<?php
function extractHtmlTag_into_array(string $htmlStr, string $tagname)
{
preg_match_all("#<\s*?$tagname\b[^>]*>.*?</$tagname\b[^>]*>#s", $htmlStr , $matches);
return $matches[0];
}
$str = '<p>test</p>test.com<span>testing string</span>';
$res = extractHtmlTag_into_array($str, 'a');
print_r($res);
//output:- Array([0] => "amazon.in/xyz/abc?test=abc")
?>
I want to search engine with LIKE keyword and i want to colored searched word.
My code is:
$result1=mysql_query("SELECT * FROM archives1 where title like '%$search%' || author like '%$search%'") or die (mysql_error());
while($row1=mysql_fetch_array($result1))
{
extract($row1);
echo" <table width='456' height='151' style='table-layout:fixed;'>
<tr><td align='center'>Archives</td></tr>
<tr><td height='38'><b>Section:</b></td><td width='334'>$section</td></tr>
<tr><td height='38'><b>Title:</b></td><td width='334'>$title</td></tr>
<tr><td height='38'><b>Author:</b></td><td width='334'>$author</td></tr>
<tr><td height='38'><b>Country:</b></td><td width='334'>$country</td></tr>
<tr><td height='38'><b>Page Number:</b></td><td width='334'>$pgno</td></tr>";
If i want to search any word with above code then it gives true answer but i want answer with colored text. Only search word should be colored.
How can it be possible?
I have no idea.
use a preg_replace to replace the searched text with a span and add a class to it.
$text = 'sample text';
$query = 'text';
$text = preg_replace('/('.$query.')/','<span class="highlight">$1</span>',$text);
echo $text;
use the highlight class to style the result.
You can use a simple function to highlight arbitrary text:
// Replace string and highlight it
function highlight_words($string, $words, $css_class)
{
//convert searched word to array
$words = array($words);
//cycle
foreach ( $words as $word ) {
$string = str_ireplace($word, '<span class="'.$css_class.'">'.$word.'</span>', $string);
}
/*** return the highlighted string ***/
return $string;
}
Example usage:
$string = 'This text will highlight PHP and SQL and sql but not PHPRO or MySQL or sqlite';
$words = array('php', 'sql');
$string = highlightWords($string, $words, 'highlight');
I have a great little script that will search a file and replace a list of words with their matching replacement word. I have also found a way to prevent preg_replace from replacing those words if they appear in anchor tags, img tags, or really any one tag I specify. I would like to create an OR statement to be able to specify multiple tags. To be clear, I would like to prevent preg_replace from replacing words that not only appear in an anchor tag, but any that appear in an anchor,link,embed,object,img, or span tag. I tried using the '|' OR operator at various places in the code with no success.
<?php
$data = 'somefile.html';
$data = file_get_contents($data);
$search = array ("/(?!(?:[^<]+>|[^>]+<\/a>))\b(red)\b/is","/(?!(?:[^<]+>|[^>]+<\/a>))\b(white)\b/is","/(?!(?:[^<]+>|[^>]+<\/a>))\b(blue)\b/is");
$replace = array ('Apple','Potato','Boysenberry');
echo preg_replace($search, $replace, $data);?>
print $data;
?>
looking at the first search term which basically says to search for "red" but not inside :
"/(?!(?:[^<]+>|[^>]+<\/a>))\b(red)\b/is"
I am trying to figure out how I can somehow add <\/link>,<\/embed>,<\/object>,<\/img> to this search so that preg_replace doesn't replace 'red' in any of those tags either.
Something like this?:
<?php
$file = 'somefile.html';
$data = file_get_contents($file);
print "Before:\n$data\n";
$from_to = array("red"=>"Apple",
"white"=>"Potato",
"blue"=>"Boysenberry");
$tags_to_avoid = array("a", "span", "object", "img", "embed");
$patterns = array();
$replacements = array();
foreach ($from_to as $from=>$to) {
$patterns[] = "/(?!(?:[^<]*>|[^>]+<\/(".implode("|",$tags_to_avoid).")>))\b".preg_quote($f
rom)."\b/is";
$replacements[] = $to;
}
$data = preg_replace($patterns, $replacements, $data);
print "After:\n$data\n";
?>
Result:
Before:
red
<span class="blue">red</span>
blue<div class="blue">white</div>
<div class="blue">red</div>
After:
red
<span class="blue">red</span>
Boysenberry<div class="blue">Potato</div>
<div class="blue">Apple</div>
I am using this class to highlight the search keywords on a piece of text:
class highlight
{
public $output_text;
function __construct($text, $words)
{
$split_words = explode( " " , $words );
foreach ($split_words as $word)
{
$text = preg_replace("|($word)|Ui" ,
"<font style=\"background-color:yellow;\"><b>$1</b></font>" , $text );
}
$this->output_text = $text;
}
}
If
$text = "Khalil, M., Paas, F., Johnson, T.E., Su, Y.K., and Payer, A.F. (2008.) Effects of Instructional Strategies Using Cross Sections on the Recognition of Anatomical Structures in Correlated CT and MR Images. <i>Anatomical Sciences Education, 1(2)</i>, 75-83 "
which already contains HTML tags, and some of my search keywords are
$words = "Effects color"
The first look will highlight the word Effects, with <font style="background-color:yellow">Effect</font>, but the second loop will highlight the word color in the HTML tag. What should I do?
Is it possible to tell preg_replace to only highlight text when its not inside an alligator bracket?
Use a HTML parser to make sure that you only search through text.
You could use a CSS highlighted class instead and then use span tags, eg.
<span class="highlighted">word</span>
Then define your highlighted class in CSS. You could then exclude the word 'highlighted' from being valid in your search. Of course renaming the class to something obscure would help.
This also has the benefit of allowing you to change the highlight colour easily in the future, or indeed allowing the user to toggle it on and off by modifying the CSS.
Why use a loop?
function __construct($text, $words)
{
$split_words = preg_replace("\s+", "|", $words);
$this->output_text = preg_replace("/($split_words)/i" ,
"<font style=\"background-color:yellow; font-weight:bold;\">$1</font>" , $text );
}
A possible work-around would be to first wrap it with characters, which would (to 99%) not be a search input and replace those characters with the html tags after the 'foreach' loop:
class highlight
{
public $output_text;
function __construct($text, $words)
{
$split_words = explode(" ", $words);
foreach ($split_words as $word)
{
$text = preg_replace("|($word)|Ui", "%$1~", $text);
}
$text = str_replace("~", "</b></span>", str_replace("%", "<span style='background-color:yellow;'><b>", $text));
$this->output_text = $text;
}
}