I'm using this function to convert text to title case:
function strtotitle($title) {
$smallwordsarray = array( 'of','a','the','and','an','or','nor','but','is','if','then','else','when', 'at','from','by','on','off','for','in','to','into','with','it', 'as' );
// Split the string into separate words
$words = explode(' ', $title);
foreach ($words as $key => $word) {
// If this word is the first, or it's not one of our small words, capitalise it
// with ucwords().
if ($key == 0 or !in_array($word, $smallwordsarray))
$words[$key] = ucwords($word);
}
// Join the words back into a string
$newtitle = implode(' ', $words);
return $newtitle;
}
The issue is that if text is bold, italic etc then the function does not work and will not title case the word.
For example: "This is a simple sentence" will be converted to "This is a Simple Sentence". But "This is a simple sentence" will be converted to "This is a simple Sentence".
Any help greatly appreciated.
If you are talking about HTML tags and you want to save it, you can use this implementation:
<?php
/* Your old string */
$string = "<b>asd</b>";
/* Remove html code */
$old = strip_tags($string);
/* Upper case the first letter */
$new = ucfirst($old);
/* Replace old word to new word in $string */
$real = str_replace($old,$new,$string);
/* Here the new string and the old string */
echo $real." ".$string;
?>
So the solution in your code looks like :
function strtotitle($title) {
$smallwordsarray = array( 'of','a','the','and','an','or','nor','but','is','if','then','else','when', 'at','from','by','on','off','for','in','to','into','with','it', 'as' );
// Split the string into separate words
$words = explode(' ', $title);
foreach ($words as $key => $word) {
// If this word is the first, or it's not one of our small words, capitalise it
// with ucwords().
if ($key == 0 or !in_array(strip_tags($word), $smallwordsarray)) {
$old = strip_tags($word);
$new = ucfirst($old);
$words[key] = str_replace($old,$new,$word);
}
}
// Join the words back into a string
$newtitle = implode(' ', $words);
return $newtitle;
}
<?php
function strtotitle($title) {
$smallwordsarray = array( 'of','a','the','and','an','or','nor','but','is','if','then','else','when', 'at','from','by','on','off','for','in','to','into','with','it', 'as' );
$words = $temp = explode(' ', strip_tags($title));
foreach ($temp as $key => $word) {
if ($key == 0 or !in_array($word, $smallwordsarray)) $temp[$key] = ucwords($word);
}
foreach($words as $index => $word) $title = str_replace($word, $temp[$index], $title);
return $title;
}
var_dump(strtotitle('This is a simple sentence'));
var_dump(strtotitle('This is a <b>simple</b> <i>sentence</i>'));
You could use strip_tags this way:
function strtotitle($title) {
$smallwordsarray = array( 'of','a','the','and','an','or','nor','but','is','if','then','else','when', 'at','from','by','on','off','for','in','to','into','with','it', 'as' );
// Remove HTML tags
$titleWithoutTags = strip_tags($title);
// Split the string into separate words
$words = explode(' ', $titleWithoutTags);
foreach ($words as $key => $word) {
// If this word is the first, or it's not one of our small words, capitalise it
// with ucwords().
if ($key == 0 or !in_array($word, $smallwordsarray))
$words[$key] = ucwords($word);
}
// Join the words back into a string
$newtitle = implode(' ', $words);
return $newtitle;
}
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;
}
I tried most of solution answered here but all of them have same problem which is my question here.
I use this function for highligh search results:
function highlightWords($searchtext, $searchstrings){
$searchstrings = preg_replace('/\s+/', ' ', trim($searchstrings));
$words = explode(' ', $searchstrings);
$highlighted = array();
foreach ( $words as $word ){
$highlighted[] = "<font color='#00f'><b>".$word."</b></font>";
}
return str_replace($words, $highlighted, $searchtext);
}
Problem occurs when i search text with 2 or more strings separated with spaces and any of them have any of HTML code from my highlighted array.
For example, searchtext="I have max system performance" AND searchstrings="max f"
In first iteration foreach will replace every max with <font color='#00f'><b>max</b></font>
In second iteration it will replace every f with <font color='#00f'><b>f</b></font>
Second iteration will also replace html tags inserted in first replacement!
So it will replace f in string <font color='#00f'> also?
Any suggestion?
Thanks
Miodrag
<?php
$searchtext = "I have max system performance";
$searchstrings = "max f";
$searchstrings = preg_replace('/\s+/', ' ', trim($searchstrings));
$words = explode(' ', $searchstrings);
$highlighted = array();
foreach ( $words as $word ){
$highlighted[] = "<font color='#00f'><b>".$word."</b></font>";
}
echo strtr($searchtext, array_combine($words, $highlighted));
?>
Maybe this is good Solution for you?
function highlightWords($searchtext, $searchstrings){
$searchstrings = preg_replace('/\s+/', ' ', trim($searchstrings));
$words = explode(' ', $searchstrings);
$highlighted = array();
foreach ( $words as $word ){
$highlighted[] = '<span class="highlighted-word">'.$word.'</span>';
}
return str_replace($words, $highlighted, $searchtext);
}
echo highlightWords('I have max system performance', 'max f');
?>
You need to add a little bit CSS on your Page:
<style>
.highlighted-word {
font-weight: bold;
}
</style>
Outputs:
I have max system performance
---
UPDATE:
If you like to hightlight the complete word, look at this:
function highlightCompleteWords($searchtext, $searchstrings){
$searchstrings = preg_replace('/\s+/', ' ', trim($searchstrings));
$words = explode(' ', $searchstrings);
$highlighted = array();
foreach ( $words as $word ){
$searchtext = preg_replace("/\w*?".preg_quote($word)."\w*/i", "<span class='highlighted-word'>$0</span>", $searchtext);
}
return $searchtext;
}
echo highlightCompleteWords('I have max system performance', 'max f');
Outputs: I have max system performance
I might not fully understand your question, but I guess you want to highlight every matched word in the search string.
You could probably just do something like:
$returnString = $searchtext;
foreach ( $words as $word ){
$returnString = preg_replace('/\b'.$word.'\b/i', "<font color='#00f'><b>$0</b></font>", $returnString);
}
return $returnString;
This would output: "I have max system performance"
Since the "f" wouldn't get matched
EDIT - This is if you wanna match part of a word as well.
Kind of ugly but I believe this will fork for you
$returnString = $searchtext;
foreach ( $words as $word ){
if(strlen($word)>2){
$returnString = preg_replace('/'.$word.'/i', "§§§$0###", $returnString);
}
}
$returnString = preg_replace("/\§§§/","<font color='#00f'><b>", $returnString);
$returnString = preg_replace("/\###/","</b></font>", $returnString);
return $returnString;
Try the following
foreach ( $words as $word ){
if(strlen ($word)>2)
{
$highlighted[] = "<font color='#00f'><b>".$word."</b></font>";
}
}
I am displaying search results on site where users can search for specific keyword, words.
On results page I am trying to Highlight the searched words , in the result.
So user can get idea which words matched where.
e.g.
if user searches for : mango
the resulting item original : This Post contains Mango.
the resulting output I want of highlighted item : This Post contains <strong>Mango</strong>
I am using it like this.
<?php
//highlight all words
function highlight_words( $title, $searched_words_array) {
// loop through searched_words_array
foreach( $searched_words_array as $searched_word ) {
$title = highlight_word( $title, $searched_word); // highlight word
}
return $title; // return highlighted data
}
//highlight single word with color
function highlight_word( $title, $searched_word) {
$replace = '<strong>' . $searched_word . '</strong>'; // create replacement
$title = str_ireplace( $searched_word, $replace, $title ); // replace content
return $title; // return highlighted data
}
I am getting searched words from Sphinx Search Engine , the issue is Sphinx returns entered/macthed words in lowercase.
So by using above code , my
results becomes : This Post contains <strong>mango</strong>
*notice the m from mango got lowercase.
So my question is how can I Highlight word i.e. wrap <strong> & </strong> around the words matching the Searched words ?
without loosing its textcase ?
*ppl. its not same questions as how to highlight search results , I am asking my keywords array is in lowercase and using above method the original word gets replaced by lowercase word.
so how can I stop that ?
the other question link will face this too , because the searched keywords are in lowercase. and using str_ireplace it will match it and replace it with lowercase word.
update :
i have combined various code snippets to get what i was expecting code to do.,
for now its working great.
function strong_words( $title, $searched_words_array) {
//for all words in array
foreach ($searched_words_array as $word){
$lastPos = 0;
$positions = array();
//find all positions of word
while (($lastPos = stripos($title, $word, $lastPos))!== false) {
$positions[] = $lastPos;
$lastPos = $lastPos + strlen($word);
}
//reverse sort numeric array
rsort($positions);
// highlight all occurances
foreach ($positions as $pos) {
$title = strong_word($title , $word, $pos);
}
}
//apply strong html code to occurances
$title = str_replace('#####','</strong>',$title);
$title = str_replace('*****','<strong>',$title);
return $title; // return highlighted data
}
function strong_word($title , $word, $pos){
//ugly hack to not use <strong> , </strong> here directly, as it can get replaced if searched word contains charcters from strong
$title = substr_replace($title, '#####', $pos+strlen($word) , 0) ;
$title = substr_replace($title, '*****', $pos , 0) ;
return $title;
}
$title = 'This is Great Mango00lk mango';
$words = array('man','a' , 'go','is','g', 'strong') ;
echo strong_words($title,$words);
Regex solution:
function highlight_word( $title, $searched_word) {
return preg_replace('#('.$searched_word.')#i','<strong>\1<strong>',$title) ;
}
Just be wary of special characters that may be interpreted as meta characters in $searched_word
Here's a code snippet I wrote a while back that's working to do exactly what you want:
if(stripos($result->question, $word) !== FALSE){
$word_to_highlight = substr($result->question, stripos($result->question, $word), strlen($word));
$result->question = str_replace($word_to_highlight, '<span class="search-term">'.$word_to_highlight.'</span>', $result->question);
}
//will find all occurances of all words and make them strong in html
function strong_words( $title, $searched_words_array) {
//for all words in array
foreach ($searched_words_array as $word){
$lastPos = 0;
$positions = array();
//find all positions of word
while (($lastPos = stripos($title, $word, $lastPos))!== false) {
$positions[] = $lastPos;
$lastPos = $lastPos + strlen($word);
}
//reverse sort numeric array
rsort($positions);
// highlight all occurances
foreach ($positions as $pos) {
$title = strong_word($title , $word, $pos);
}
}
//apply strong html code to occurances
$title = str_replace('#####','</strong>',$title);
$title = str_replace('*****','<strong>',$title);
return $title; // return highlighted data
}
function strong_word($title , $word, $pos){
//ugly hack to not use <strong> , </strong> here directly, as it can get replaced if searched word contains charcters from strong
$title = substr_replace($title, '#####', $pos+strlen($word) , 0) ;
$title = substr_replace($title, '*****', $pos , 0) ;
return $title;
}
$title = 'This is Great Mango00lk mango';
$word = array('man','a' , 'go','is','g', 'strong') ;
echo strong_words($title,$word);
This code will find all occurrences of all words and make them strong in html while keeping original text case.
function highlight_word( $content, $word, $color ) {
$replace = '<span style="background-color: ' . $color . ';">' . $word . '</span>'; // create replacement
$content = str_replace( $word, $replace, $content ); // replace content
return $content; // return highlighted data
}
function highlight_words( $content, $words, $colors ) {
$color_index = 0; // index of color (assuming it's an array)
// loop through words
foreach( $words as $word ) {
$content = highlight_word( $content, $word, $colors[$color_index] ); // highlight word
$color_index = ( $color_index + 1 ) % count( $colors ); // get next color index
}
return $content; // return highlighted data
}
// words to find
$words = array(
'normal',
'text'
);
// colors to use
$colors = array(
'#88ccff',
'#cc88ff'
);
// faking your results_text
$results_text = array(
array(
'ab' => 'AB #1',
'cd' => 'Some normal text with normal words isn\'t abnormal at all'
), array(
'ab' => 'AB #2',
'cd' => 'This is another text containing very normal content'
)
);
// loop through results (assuming $output1 is true)
foreach( $results_text as $result ) {
$result['cd'] = highlight_words( $result['cd'], $words, $colors );
echo '<fieldset><p>ab: ' . $result['ab'] . '<br />cd: ' . $result['cd'] . '</p></fieldset>';
}
Original link check here
In the event of a string that says:
Once upon a time a small young LKTgoblingLKT had an unfortunate accident and LKTfellLKT.
How could I extract each occurrence of content contained within LKT into an array and replace them in the string.
You can try the following solution:
Store the sentence in a variable
explode() the sentence with space as the delimiter
Loop through the array
Check if the word contains your string using strpos()
If it does, push the word into the result array
Something like this:
$string = '...';
$words = explode(' ', $string);
foreach ($words as $word) {
if (strpos($word, 'LKT') !== FALSE) {
$result[] = $word;
}
}
print_r($result);
Output:
Array
(
[0] => LKTgoblingLKT
[1] => LKTfellLKT.
)
Demo!
If you want the string to be replaced with another word, you can use str_replace() and implode(), like so:
$string = '...';
$words = explode(' ', $string);
$result = array();
foreach ($words as $word) {
if (strpos($word, 'LKT') !== FALSE) {
$word = str_replace($word, 'FOO', $word);
}
$result[] = $word;
}
$resultString = implode(' ', $result);
echo $resultString;
Output:
Once upon a time a small young FOO had an unfortunate accident and FOO
Demo!
I am trying to test if a string made up of multiple words and has any values from an array at the end of it. The following is what I have so far. I am stuck on how to check if the string is longer than the array value being tested and that it is present at the end of the string.
$words = trim(preg_replace('/\s+/',' ', $string));
$words = explode(' ', $words);
$words = count($words);
if ($words > 2) {
// Check if $string ends with any of the following
$test_array = array();
$test_array[0] = 'Wizard';
$test_array[1] = 'Wizard?';
$test_array[2] = '/Wizard';
$test_array[4] = '/Wizard?';
// Stuck here
if ($string is longer than $test_array and $test_array is found at the end of the string) {
Do stuff;
}
}
By end of string do you mean the very last word? You could use preg_match
preg_match('~/?Wizard\??$~', $string, $matches);
echo "<pre>".print_r($matches, true)."</pre>";
I think you want something like this:
if (preg_match('/\/?Wizard\??$/', $string)) { // ...
If it has to be an arbitrary array (and not the one containing the 'wizard' strings you provided in your question), you could construct the regex dynamically:
$words = array('wizard', 'test');
foreach ($words as &$word) {
$word = preg_quote($word, '/');
}
$regex = '/(' . implode('|', $words) . ')$/';
if (preg_match($regex, $string)) { // ends with 'wizard' or 'test'
Is this what you want (no guarantee for correctness, couldn't test)?
foreach( $test_array as $testString ) {
$searchLength = strlen( $testString );
$sourceLength = strlen( $string );
if( $sourceLength <= $searchLength && substr( $string, $sourceLength - $searchLength ) == $testString ) {
// ...
}
}
I wonder if some regular expression wouldn't make more sense here.