I am using the following code to pull some keywords and add them as tags in wordpress.
if (!is_array($keywords)) {
$count = 0;
$keywords = explode(',', $keywords);
}
foreach($keywords as $thetag) {
$count++;
wp_add_post_tags($post_id, $thetag);
if ($count > 3) break;
}
The code will fetch only 4 keywords, However on top of that, I want to pull ONLY if they are higher than 2 characters, so i dont get tags with 2 letters only.
Can someone help me.
strlen($string) will give you the lenght of the string:
if (!is_array($keywords)) {
$count = 0;
$keywords = explode(',', $keywords);
}
foreach($keywords as $thetag) {
$thetag = trim($thetag); // just so if the tags were "abc, de, fgh" then de won't be selected as a valid tag
if(strlen($thetag) > 2){
$count++;
wp_add_post_tags($post_id, $thetag);
}
if ($count > 3) break;
}
Use strlen to check the length.
int strlen ( string $string )
Returns the length of the given string.
if(strlen($thetag) > 2) {
$count++;
wp_add_post_tags($post_id, $thetag);
}
Related
i need to write a search engine. And i had occurred some prbolems with it.
so for now my query looks like this.
SELECT * FROM umowy WHERE keywords LIKE ('%propanek%' OR '%seba%')
And i making this, with this example of code. (two words for now)
$szukaj = $_POST['szukaj'];
$szukaj_trim = trim($szukaj);
$szukaj_array = explode(" ",$szukaj_trim);
$szukaj_length = count($szukaj_array);
if ($szukaj_length === 1 ) {
$constr = "('%${szukaj_array[0]}%')";
}
else{
for($i = 0; $i <= $szukaj_length; $i++){
if($i == 0){
$constr = $constr."('%${szukaj_array[${i}]}%'";
}
if($i > 0 && $i < ($szukaj_length-1)){
$constr = $constr." OR '%${szukaj_array[${i}]}%'";
}
if ($i == ($szukaj_length-1)) {
$constr = $constr." OR '%${szukaj_array[${i}]}%')";
}
}
}
$query="SELECT * FROM umowy WHERE keywords LIKE $constr";
Is there way to reduce a result output by adding more words in search input?
Now it's working like "more words, more content to show". But i need something opposite, more words, the more accurate result is.
(sorry for my not perfect english)
I had a PHP string which contains English words. I want to extract all the possible words from the string, not by explode() by space as I have only a word. I mean extraction of words from a word.
Example: With the word "stackoverflow", I need to extract stack, over, flow, overflow all of them.
I am using pspell_check() for spell checking. I am currently getting the following combination.
--> sta
--> stac
--> stack
and so on.
So I found the only the words matching stack but I want to find the following words. Notice that I don't want the final word as I've already.
--> stack
--> over
--> flow
My Code:
$myword = "stackoverflow";
$word_length = strlen($myword);
$myword_prediction = $myword[0].$myword[1];
//(initial condition as words detection starts after 3rd index)
for ($i=2; $i<$word_length; $i++) {
$myword_prediction .= $myword[$i];
if (pspell_check(pspell_new("en"), $myword_prediction))
{
$array[] = $myword_prediction;
}
}
var_dump($array);
How about if you have an outer loop like this. The first time through you start at the first character of $myword. The second time through you start at the second character, and so on.
$myword = "stackoverflow";
$word_length = strlen($myword);
$startLetter = 0;
while($startLetter < $word_length-2 ){
$myword_prediction = $myword[$startLetter] . $myword[$startLetter +1];
for ($i=$startLetter; $i<$word_length; $i++) {
$myword_prediction .= $myword[$i];
if (pspell_check(pspell_new("en"), $myword_prediction)) {
$array[] = $myword_prediction;
}
}
$startLetter ++;
}
Well, you would need to get all substrings, and check each one:
function get_all_substrings($input){
$subs = array();
$length = strlen($input);
for($i=0; $i<$length; $i++){
for($j=$i; $j<$length; $j++){
$subs[] = substr($input, $i, $j);
}
}
return array_unique($subs);
}
$substrings = get_all_substrings("stackoverflow");
$pspell_link = pspell_new("en");
$words = array_filter($substrings, function($word) use ($pspell_link) {
return pspell_check($pspell_link, $word);
});
var_dump($words);
Just like the title of this post says, I would to be able to check if every letter of a word is found in another word. So far these are the lines of codes that I was able to come up with:
<?php
$DBword = $_POST['DBword'];
$inputWords = $_POST['inputWords'];
$inputCount = str_word_count($inputWords,1);
echo "<b>THE WORD:</b>"."<br/>".$DBword."<br/><br/>";
echo "<b>WORDS ENTERED:</b><br/>";
foreach($inputCount as $outputWords)
{
echo $outputWords."<br/>";
}
foreach($inputCount as $countWords)
{
for($i=0; $i<strlen($countWords); $i++)
{$count = strpos( "$DBword", $countWords[$i]);}
if($count === false)
{
$score++;
}
}
echo "<b><br/>TOTAL SCORE: </b>";
echo $score;
?>
My point in having the foreach with the $outputWords is to just output the letters entered.
As for the other foreach that has $countWords, I am using it to really check if all letters in the word entered are found in the $DBword. I am using the for loop to check every letter.
So far, I am not getting the output that I want and I just ran out of ideas. Any ideas please?
function contains_letters($word1, $word2) {
for ($i = 0; $i < strlen($word1); $i++)
if (strpos($word2, $word1{$i}) === false)
return false;
return true;
}
//example usage
if (contains_letters($_POST['inputWords'], $_POST['DBword']))
echo "All the letters were found.";
If this check should be case-insensitive (i.e. 'A' counts as a usage of 'a'), change strpos to stripos.
Since you are overwriting $count in the for loop for each letter in $countWords, $count will contain the position of the last letter of $countWord only. Also, I am not sure why you increase score when the letter wasn't found.
In any case, you are making your life more difficult than necessary.
PHP has a function for counting chars in a string:
return count_chars($dbWord, 3) === count_chars($inputWord, 3);
will return true if the same letters are found in both strings.
Example to find all the words having exactly the same letters:
$dbWord = count_chars('foobar', 3);
$inputWords = 'barf boo oof raboof boarfo xyz';
print_r(
array_filter(
str_word_count($inputWords, 1),
function($inputWord) use ($dbWord) {
return count_chars($inputWord, 3) === $dbWord;
}
)
);
will output "raboof" and "boarfo" only.
I have an interesting problem where I am highlighting text from a keyword array using PHP's str_ireplace().
Let's say this is my array of keywords or phrases that I want to highlight from a sample text:
$keywords = array('eggs', 'green eggs');
And this is my sample text:
$text = 'Green eggs and ham.';
Here is how I am highlighting the text:
$counter = 0;
foreach ($keywords as $keyword) {
$text = str_ireplace($keyword, '<span class="highlight_'.($counter%5).'">'.$keyword.'</span>', $text);
$counter++;
}
The problem with this is that green eggs will never get a match because eggs has already been replaced in the text as:
Green <span class="highlight_0">eggs</span> and ham.
There may also be cases where there is partial overlaps such as:
$keywords = array('green eggs', 'eggs and');
What is a smart way to tackle this sort of issue?
Reverse the order:
$keywords = array('green eggs', 'eggs');
The simplest way is to do the longest strings first and move on to shorter ones after. Just make sure you don't double-over the same string (if it matters).
Maybe this is not the prettiest solution, but you could track the locations where your keywords occur, and then find where they overlap and adjust where you want to include the span tags
$keywords = array('eggs', 'n eggs a', 'eggs and','green eg');
$text = 'Green eggs and ham.';
$counter = 0;
$idx_array = array();
$idx_array_last = array();
foreach ($keywords as $keyword) {
$idx_array_first[$counter] = stripos($text, $keyword);
$idx_array_last[$counter] = $idx_array_first[$counter] + strlen($keyword);
$counter++;
}
//combine the overlapping indices
for ($i=0; $i<$counter; $i++) {
for ($j=$counter-1; $j>=$i+1; $j--) {
if (($idx_array_first[$i] <= $idx_array_first[$j] && $idx_array_first[$j] <= $idx_array_last[$i])
|| ($idx_array_last[$i] >= $idx_array_last[$j] && $idx_array_first[$i] <= $idx_array_last[$j])
|| ($idx_array_first[$j] <= $idx_array_first[$i] && $idx_array_last[$i] <= $idx_array_last[$j])) {
$idx_array_first[$i] = min($idx_array_first[$i],$idx_array_first[$j]);
$idx_array_last[$i] = max($idx_array_last[$i],$idx_array_last[$j]);
$counter--;
unset($idx_array_first[$j],$idx_array_last[$j]);
}
}
}
array_multisort($idx_array_first,$idx_array_last); //sort so that span tags are inserted at last indices first
for ($i=$counter-1; $i>=0; $i--) {
//add span tags at locations of indices
$textnew = substr($text,0,$idx_array_first[$i]).'<span class="highlight_'.$i.'">';
$textnew .=substr($text,$idx_array_first[$i],$idx_array_first[$i]+$idx_array_last[$i]);
$textnew .='</span>'.substr($text,$idx_array_last[$i]);
$text = $textnew;
}
Output is
<span class="highlight_0">Green eggs and</span> ham.
I take a sentence as input like this:
abcd 01234 87 01235
Next, I have to check every word to see if its characters are consecutive in the alphabet. The output looks like this:
abcd 01234
Well, 01235 contains consecutive chars, but the whole word ALSO contains non-consecutive chars (35), so it's not printed on the screen.
So far I wrote this:
function string_to_ascii($string)
{
$ascii = NULL;
for ($i = 0; $i < strlen($string); $i++)
{
$ascii[] = ord($string[$i]);
}
return($ascii);
}
$input = "abcd 01234 87 01235";
//first, we split the sentence into separate words
$input = explode(" ",$input);
foreach($input as $original_word)
{
//we need it clear
unset($current_word);
//convert current word into array of ascii chars
$ascii_array = string_to_ascii($original_word);
//needed for counting how many chars are already processed
$i = 0;
//we also need to count the total number chars in array
$ascii_count = count($ascii_array);
//here we go, checking each character from array
foreach ($ascii_array as $char)
{
//if IT'S THE LAST WORD'S CHAR
if($i+1 == $ascii_count)
{
//IF THE WORD HAS JUST 1 char, output it
if($ascii_count == 1)
{
$current_word .= chr($char);
}
//IF THE WORDS HAS MORE THAN 1 CHAR
else
{
//IF PREVIOUS CHAR CODE IS (CURRENT_CHAR-1) (CONSECUTIVE, OUTPUT IT)
if(($char - 1) == $ascii_array[($i-1)])
{
$current_word .=chr($char);
}
}
}
//IF WE AREN'T YET AT THE ENDING
else
{
//IF NEXT CHAR CODE IS (CURRENT_CHAR+1) (CONSECUTIVE, OUTPUT IT)
if(($char + 1) == ($ascii_array[($i+1)]))
{
$current_word .=chr($char);
}
}
$i++;
}
//FINALLY, WE CHECK IF THE TOTAL NUMBER OF CONSECUTIVE CHARS is the same as THE NUMBER OF CHARS
if(strlen($current_word) == strlen($original_word))
{
$output[] = $current_word;
}
}
//FORMAT IT BACK AS SENTENCE
print(implode(' ',$output));
But maybe there is another way to do this, more simple?
sorry for bad spelling
This works...
$str = 'abcd 01234 87 01235';
$words = explode(' ', $str);
foreach($words as $key => $word) {
if ($word != implode(range($word[0], chr(ord($word[0]) + strlen($word) - 1)))) {
unset($words[$key]);
}
}
echo implode(' ', $words);
CodePad.
Basically, it grabs the first character of each word, and creates the range of characters which would be the value if the word consisted of sequential characters.
It then does a simple string comparison.
For a more performant version...
$str = 'abcd 01234 87 01235';
$words = explode(' ', $str);
foreach($words as $key => $word) {
foreach(str_split($word) as $index => $char) {
$thisOrd = ord($char);
if ($index > 0 AND $thisOrd !== $lastOrd + 1) {
unset($words[$key]);
break;
}
$lastOrd = $thisOrd;
}
}
echo implode(' ', $words);
CodePad.
Both these examples rely on the ordinals of the characters being sequential for sequential characters. This is the case in ASCII, but I am not sure about other characters.