I wan't to create a highlight tag search function via php
when I search a part of word...whole of word be colored
for example this is a sample text:
Text: British regulators say traders used private online chatrooms to coordinate their buying and selling to shift currency prices in their favor.
when I search "th" the output be like this:
Text: British regulators say traders used private online chatrooms to coordinate their buying and selling to shift currency prices in their favor.
So...I tried this code...please help me to complete it.
This is a algorithm:
$text= "British regulators say...";
foreach($word in $text)
{
if( IS There "th" in $word)
{
$word2= '<b>'.$word.'</b>'
replace($word with word2 and save in $text)
}
}
how can I it in php language?
function highLightWords($string,$find)
{
return preg_replace('/\b('.$find.'\w+)\b/', "<b>$1</b>", $string);
}
Usage:
$string="British regulators say traders used private online chatrooms to coordinate their buying and selling to shift currency prices in their favor.";
$find="th";
print_r(highLightWords($string,$find));
Fiddle
Edit after your comment:
...How can I do it for middle characters? for example "line"
Very easy, just update the regex pattern accordingly
return preg_replace("/\b(\w*$find\w*)\b/", "<b>$1</b>", $string);
Fiddle
Use strpos() to find the position of the character you search for.. Then start reading from that identified position of character to till you don't find any space..
Should be much easier:
$word = "th";
$text = preg_replace("/\b($word.*?)\b/", "<b>$1</b>", $text);
Let's say a lot of things.
First, as you know php is a server-side code, so, as long as you won't mind reload the page each time or use ajax...
The correct way i think will be using Javascript to Achieve this.
That said to explode the text you need to use another function, to be sure of what obtained:
Something like:
$str = "Hello world. It's a beautiful day.";
$words = explode(" ",$str);
Now Words var will contain the exploded string.
Now you can loop and replace (for example) and then re-construct the string and print it or do other.
You can go with the following code
<?php
$string = "British regulators say traders used private online chatrooms to coordinate their buying and selling to shift currency prices in their favor";
$keyword = "th";
echo highlightkeyword($string , $keyword );
function highlightkeyword($str, $search) {
$occurrences = substr_count(strtolower($str), strtolower($search));
$newstring = $str;
$match = array();
for ($i=1;$i<$occurrences;$i++) {
$match[$i] = stripos($str, $search, $i);
$match[$i] = substr($str, $match[$i], strlen($search));
$newstring = str_replace($match[$i], '[#]'.$match[$i].'[#]', strip_tags($newstring));
}
$newstring = str_replace('[#]', '<b>', $newstring);
$newstring = str_replace('[#]', '</b>', $newstring);
return $newstring;
}
?>
Check here https://eval.in/220395
Related
What I'm trying to remove all data in a string before a the first occurrence of a number like (1-9) maybe in a function?
example:
$value = removeEverythingBefore($value, '1-10');
SO if i have a test like "Hello I want to rule the world in 100 hours or so"
I want this to find the first occurrence of a number which is 1 and delete everything before it.
Leaving me with 100 hours or so.
If you want to call the function like you mentioned in your post you can do like the below:
<?php
function removeEverythingBefore($value, $pattern) {
preg_match($pattern, $value, $matches, PREG_OFFSET_CAPTURE);
$initialPosition = $matches[0][1];
return substr($value, $initialPosition);
}
$value = "Hello I want to rule the world in 100 hours or so";
$value = removeEverythingBefore($value, '/[0-9]/');
echo $value; // prints 100 hours or so
This way you can use the same function to match other patters aswell.
You can use preg_replace for this with the regex /([a-z\s]*)(?=\d)/i like this:
$string = "Hello I want to rule the world in 100 hours or so";
$newString = preg_replace("/([a-z\s]*)(?=\d)/i", "", $string);
echo $newString; // Outputs "100 hours or so"
You can see an it working with this eval.in. If you wanted it in a function you could use this:
function removeEverythingBeforeNumber($string)
{
return preg_replace("/([a-z\s]*)(?=\d)/i", "", $string);
}
$newString = removeEverythingBeforeNumber("Hello I want to rule the world in 100 hours or so");
you could use strpos to get the index of the first occurence and then substr to get the string beginning from that index. Would be faster/more hardware friendly then regex i believe.
I want to get sentence(s) which include(s) searched word(s). I have tried this but can't make it work properly.
$string = "I think instead of trying to find sentences, I'd think about the amount of
context around the search term I would need in words. Then go backwards some fraction of this number of words (or to the beginning) and forward the remaining number
of words to select the rest of the context.";
$searchlocation = "fraction";
$offset = stripos( strrev(substr($string, $searchlocation)), '. ');
$startloc = $searchlocation - $offset;
echo $startloc;
You can get all sentences.
try this:
$string = "I think instead of trying to find sentences, I'd think about the amount of
context around the search term I would need in words. Then go backwards some fraction of this number of words (or to the beginning) and forward the remaining number
of words to select the rest of the context.";
$searchlocation = "fraction";
$sentences = explode('.', $string);
$matched = array();
foreach($sentences as $sentence){
$offset = stripos($sentence, $searchlocation);
if($offset){ $matched[] = $sentence; }
}
var_export($matched);
using array_filter function
$sentences = explode('.', $string);
$result = array_filter(
$sentences,
create_function('$x', "return strpos(\$x, '$searchlocation');"));
Note: the double quote in the second parameter of create_function is necessary.
If you have anonymous function support, you can use this,
$result = array_filter($sentences, function($x) use($searchlocation){
return strpos($x, $searchlocation)!==false;
});
Since you reverse the string with strrev(), you will find [space]. instead of .[space].
I have a line of text that has acronyms inside is kind of like this...
$draft="The war between the CIA and NSA started in K2 when the FBI hired M";
I can't for the life of me figure out how to create a new string with all acronyms removed.
I need this output...
$newdraft="The war between the and started in when the hired";
The only php functions I can find only remove words that you statically declare like this!
$newdraft= str_replace("CIA", " ", $draft);
Anyone have any ideas, or an already created function?
Ok, let's try to write something (albeit I can't understand what for it can be useful).
<?php
function remove_acronyms($str)
{
$str_arr = explode(' ', $str);
if (empty($str_arr)) return false;
foreach ($str_arr as $index => $val)
{
if ($val==strtoupper($val)) unset($str_arr[$index]);
}
return implode(' ', $str_arr);
}
$draft = "The war between the CIA and NSA started in K2 when the FBI hired M";
print remove_acronyms($draft);
http://codepad.org/cIZSwwhV
Definition of an acronym: any word that is fully capitalized, and at least 2 chars long.
<?php
$draft="The war between the CIA and NSA started in K2 when the FBI hired M";
$words = explode(' ', $draft);
foreach($words as $i => $word)
{
if (!strcmp($word, strtoupper($word)) && strlen($word) >= 2)
{
unset($words[$i]);
}
}
$clean = implode(' ', $words);
echo $clean;
?>
Try to define an acronym. You'd have to cut some corners, but stating something like 'any single word that is smaller then 5 characters and in all capitals' should be correct for this sample, and you'd be able to write a regular expression for that.
Other then that, you could make a huge list of known acronyms and just replace those.
Regex to remove multiple caps and/or numbers appearing together:
$draft="The war between the CIA and NSA started in K2 when the FBI hired M";
$newdraft = preg_replace('/[A-Z0-9][A-Z0-9]+/', '', $draft);
echo $newdraft;
Can someone tell me please how to do this:
Input:
hello http://DOMAIN.com/asdakdjk.php?asd=231&adsj=23 u.s. nicely done!
Result:
Hello http://DOMAIN.com/asdakdjk.php?asd=231&adsj=23 U.S. Nicely Done!
Including words in separated by '.' if possible such as in U.S.
Thanks
try this:
<?php
function capitalizeNonURLs($input)
{
preg_match('#(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)#', $input, $matches);
$url = $matches[1];
$temp = ucwords($input);
$output = str_ireplace($url, $url, $temp);
return $output;
}
$str = "hello http://domain.com/asdakdjk.php?asd=231&adsj=23 u.s. nicely done!";
echo capitalizeNonURLs($str);
Keep in mind that this function does not handle abbreviations (it won't change usa to USA). Country codes can be handled in several different ways. One is to make a hashmap of country codes and replace them or use regular expression for that as well.
To keep urls lower:
$strarray = explode(' ',$str);
for($i=0;$i<count($strarray))
{
if(substr($strarray[$i],0,4)!='http')
{
$strarray[$i] = ucfirst($strarray[$i])
}
}
$new_str = implode('',$strarray);
I have written the PHP code for getting some part of a given dynamic sentence, e.g. "this is a test sentence":
substr($sentence,0,12);
I get the output:
this is a te
But i need it stop as a full word instead of splitting a word:
this is a
How can I do that, remembering that $sentence isn't a fixed string (it could be anything)?
use wordwrap
If you're using PHP4, you can simply use split:
$resultArray = split($sentence, " ");
Every element of the array will be one word. Be careful with punctuation though.
explode would be the recommended method in PHP5:
$resultArray = explode(" ", $sentence);
first. use explode on space. Then, count each part + the total assembled string and if it doesn't go over the limit you concat it onto the string with a space.
Try using explode() function.
In your case:
$expl = explode(" ",$sentence);
You'll get your sentence in an array. First word will be $expl[0], second - $expl[1] and so on. To print it out on the screen use:
$n = 10 //words to print
for ($i=0;$i<=$n;$i++) {
print $expl[$i]." ";
}
Create a function that you can re-use at any time. This will look for the last space if the given string's length is greater than the amount of characters you want to trim.
function niceTrim($str, $trimLen) {
$strLen = strlen($str);
if ($strLen > $trimLen) {
$trimStr = substr($str, 0, $trimLen);
return substr($trimStr, 0, strrpos($trimStr, ' '));
}
return $str;
}
$sentence = "this is a test sentence";
echo niceTrim($sentence, 12);
This will print
this is a
as required.
Hope this is the solution you are looking for!
this is just psudo code not php,
char[] sentence="your_sentence";
string new_constructed_sentence="";
string word="";
for(i=0;i<your_limit;i++){
character=sentence[i];
if(character==' ') {new_constructed_sentence+=word;word="";continue}
word+=character;
}
new_constructed_sentence is what you want!!!