I have a text area which contains information as follows,
Secured places in the national squad respectively
Selected to the national team this year as well
Selected to the national team twice during his university career
Went to school at ABS
when user click the submit button, I want to get strings in each lines to php variables in submit page, something like this
$a = "Secured places in the national squad respectively";
$b = "Selected to the national team this year as well";
$c = "Selected to the national team twice during his university career";
$d = "Went to school at ABS";
can anyone please tell me how to do this?
If you don't care about sentences but rather line breaks, you should be able to break into an array based on that like this:
$posted_text = $_POST['text']; // or however you get the value into a string
$text_array = explode(PHP_EOL, $posted_text);
I think you looking for
explode('\n\r', $var)
where var is the value your ripping apart
Your best bet would be exploding the string via the newline character \n. Unfortunately, if the user didn't actually hit enter and the text has just rolled onto the next line, there won't be any newline characters to explode by.
Working example wihout breaking lines:
http://codepad.viper-7.com/OBiUXP
$words = explode(" ", str_replace("\n"," ",$text));
$sentences = Array();
$sentence = Array();
foreach($words as $word) {
$word = trim($word);
if(!$word) continue ;
$char1 = substr($word,0,1);
$char2 = substr($word,1,1);
if((strtoupper($char1) == $char1) && (strtolower($char2) == $char2)) {
if(count($sentence)) {
$sentences[] = join(" ", $sentence);
}
$sentence = Array();
}
$sentence[] = $word;
}
if(count($sentence)) {
$sentences[] = join(" ", $sentence);
}
Related
I am trying to highlight the strings. Whether they are in the sequence or not.
Like this -
$str = "star 5 hotel";
$keywords = "5 star hotels";
There is my function. It only highlights the last matching string.Here $str contains the search string. $keyword contains that string which i have stored into database
How can i highlight each matching string.
function highlight($str, $keyword) {
$str = "star hotel 5";
$keyword = "5 star hotel";
foreach($look as $find){
if(strpos($keyword, $find) !== false) {
if(!isset($highlight)){
$highlight[] = $find;
} else {
if(!in_array($find,$highlight)){
$highlight[] = $find;
}
}
}
}
if(isset($highlight)){
foreach($highlight as $replace){
$str = str_ireplace($replace,'<b>'.$replace.'</b>',$keyword);
$stra[] = str_ireplace($replace,'<b>'.$replace.'</b>',$keyword);
echo "<pre>";
print_r ($stra);
echo "</pre>";
}
}
echo $str."<br>";
die();
return $str;
}
But when i put this into an array and when i print this array $stra[]. It given me this
Array
(
[0] => 5 star hotel
[1] => 5 star hotel
[2] => 5 star hotel
)
I can not find way to combine these.
Output : -If have that keyword which is searching . then this must be Highlighted..
5 star hotel
This is what I assumed:-
I assume that you want to search each word of the search sting in the given string and if and only if all the words found then make string in bold (complete string).
Then do like below (Explanation given in comments):-
<?php
$search = "star 5 hotel"; //search string
$string = "5 star hotels"; // string in which you want to search
function highlight($search, $string) {
$new_search = array_unique(array_filter(explode(" " ,$search)));//explode search string
$found_count = 0; //create a counter
foreach($new_search as $find){ // iterate over search words array
if(strpos($string, $find) !== false) { // if word found in the string
$found_count +=1; // increase the counter
}
}
if(count($new_search) == $found_count){ //check that all words found in the string
$string = "<b>". $string ."</b>"; // if yes then make each word of the string bold
}
return $string; //return the newly modified string
}
echo highlight($search, $string); // echo newly modified string
Output:- https://eval.in/838325
You can use an array, and strtr() function. :)
$str = "the quick brown fox";
$keywords = "quick fox brown";
$matches = explode(" ",$keywords);
foreach ($matches as $v) {
$arr_matches[$v] = "<b>".$v."</b>";
}
$str = strtr($str, $arr_matches);
I know it's late but here is one way to make a double loop that will keep the bloat tags to a minimum and handle extra words in the sentence (in what I think is correct way).
It checks if the word is in match list, if yes loop til there is a not matching word.
Add the tags around those two words and go back to main loop.
$str = "star 5 hotel";
$strarr =explode(" ", $str);
$keywords = "a 5 star uinique hotel";
$arr = explode(" ", $keywords);
For($i=0; $i < count($arr) ; $i++){
If(in_array($arr[$i], $strarr)){
$j=$i;
While(in_array($arr[$j], $strarr) && $j < count($arr)){
$j++;
}
$j--;
$arr[$i] = "<b>" . $arr[$i];
$arr[$j] = $arr[$j] . "</b>";
$i=$j;
}
}
Echo implode(" ", $arr);
Output of above example:
a <b>5 star</b> uinique <b>hotel</b>
https://3v4l.org/pKE4X
You can use an array to achieve:
$str = 'This is some 5 start hotel in US';
$keyWords = ['5', 'star', 'hotel'];
$strToCheck = explode(' ', $str);
foreach ($keyWords as $k => $v)
{
if (in_array($v, $strToCheck)) {
//do something
}
}
this creates the string as an array, this means we can use in_array to check, then inside the if statement do whatever :)
references:
http://php.net/manual/en/function.in-array.php
http://php.net/manual/en/function.explode.php
Why don't you just iterate over your keywords and replace them:
$str = "This is a star 5 hotel located in New York";
$keywords = array("5","star","hotels");
foreach (array_expression as $key => $value){
$str = str_replace($value, "<b>".$value."</b>", $str);
}
Simple and failsafe if you don't have double keywords.
Or if your keywords need to be a something-separated string:
$str = "This is a star 5 hotel located in New York";
$keywords = "5 star hotel";
$arraykeywords = explode(" ",$keywords);
foreach (array_expression as $key => $value){
$str = str_replace($value, "<b>".$value."</b>", $str);
}
To filter double keywords use array_unique:
$str = "This is a star 5 hotel located in New York";
$keywords = "5 star hotel star";
$arraykeywords = array_unique(explode(" ",$keywords));
foreach (array_expression as $key => $value){
$str = str_replace($value, "<b>".$value."</b>", $str);
}
After a lot of discussion about regex (see the comments), this is the approach using #Andreas's regex:
$str = "This is a star 5 hotel located in New York";
$keywords = "5 star hotel star";
$pregsearch = "/".implode("|",array_unique(explode(" ",$keywords)))."/g"; //remove dups and join as regex
$str = preg_replace($pregsearch, "<b>$0</b>", $str);
Only recomended if your searching a large string.
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
I want a program in php that takes the first letter of word to the last and add "ay" at end. example:
I love my family becomes Iay ovelay ymay amilyfay
I did this to get my result:
<?php
$var = "I love my family";
$words = explode(" ",$var);
$final = "";
foreach ($words as $word){
$n = "";
for($i=1;$i<strlen($word);$i++){
$n .= $word{$i};
}
$n .= $word{0}."ay";
$final .= $n." ";
}
echo $final;
?>
but this doesnt work when the input is: he says, "I love my family". this gives output as: ehay ays,say I"ay ovelay ymay amily"fay where I need the punctuation marks to be in their own position like this: ehay ayssay, "Iay ovelay ymay amilyfay"
Tried alot but found nothing that works
Looks like something along the lines of:
$str = 'he says, "I love my family"';
$str = preg_replace('/(\w{1})(\w*)/', "$2$1ay", $str);
echo $str; // ehay ayssay, "Iay ovelay ymay amilyfay"
Should get you at least most of the way there.
Basically I'm trying to write a pretty basic program in PHP that just takes user input and translates it into Piglatin with PHP without using regular expressions. This is what my code so far looks like, which is fine:
<?php # script
$original = $_REQUEST['original'];
$array = explode(" ", $original);
$piglatin = "";
foreach($array as $word)
{
$word = trim($word);
$first = substr($word,0,1);
$thsh = substr($word,1,2);
$thshrest = substr($word,2, strlen($word)-2);
$rest = substr($word,1,strlen($word)-1);
if(trim($word))
{
$piglatin .= (strlen($word)==1)?$first." ":$rest.$first. "ay ";
}
}
echo $original ." becomes: ".$piglatin;
?>
except it doesn't take into account the special cases, like if a word begins with a vowel (in which case, the word "igloo" for example should be printed as "iglooway"), or if it begins with "th" or "sh" (in which case, the word "thimble" for example should be printed as "imblethay", taking the first two letters and bringing them to the end instead of just the first one.)
I've already started the process of creating variables out of the strings that start with "th" and "sh" (see $thsh and $thshrest), but I'm really confused as to where I should go from here?
A regex solution (probably not what you want, but I want to show just how easy it is):
$pig_latin = preg_replace('#^([^aeiou]+)([aeiou]+)(.*)#', '$2$3$1ay', $original);
$pig_latin = preg_replace('#(^[aeiou].*)#', '$1way', $pig_latin);
How about:
foreach ($array as $word) {
if (preg_match('/^[aeiou]/', $word)) {
$word = preg_replace('/^([aeiou].+)$/', "$1way", $word);
} else {
$word = preg_replace('/^(th|sh)(.+)$/', "$2$1ay", $word);
}
$piglatin .= $word ." ";
}
here's the line of code that I came up with:
function Count($text)
{
$WordCount = str_word_count($text);
$TextToArray = explode(" ", $text);
$TextToArray2 = explode(" ", $text);
for($i=0; $i<$WordCount; $i++)
{
$count = substr_count($TextToArray2[$i], $text);
}
echo "Number of {$TextToArray2[$i]} is {$count}";
}
So, what's gonna happen here is that, the user will be entering a text, sentence or paragraph. By using substr_count, I would like to know the number of occurrences of the word inside the array. Unfortunately, the output the is not what I really need. Any suggestions?
I assume that you want an array with the word frequencies.
First off, convert the string to lowercase and remove all punctuation from the text. This way you won't get entries for "But", "but", and "but," but rather just "but" with 3 or more uses.
Second, use str_word_count with a second argument of 2 as Mark Baker says to get a list of words in the text. This will probably be more efficient than my suggestion of preg_split.
Then walk the array and increment the value of the word by one.
foreach($words as $word)
$output[$word] = isset($output[$word]) ? $output[$word] + 1 : 1;
If I had understood your question correctly this should also solve your problem
function Count($text) {
$TextToArray = explode(" ", $text); // get all space separated words
foreach($TextToArray as $needle) {
$count = substr_count($text, $needle); // Get count of a word in the whole text
echo "$needle has occured $count times in the text";
}
}
$WordCounts = array_count_values(str_word_count(strtolower($text),2));
var_dump($WordCounts);