php foreach counting new lines (\n) - php

If I have a piece of code that works like this:
$i = 0;
$names = explode(",", $userInput);
foreach($names as $name) {
$i++;
}
It works perfectly, provided the user has placed a comma after each name entered into the html textarea this comes from. But I want to make it more user friendly and change it so that each name can be entered on a new line and it'll count how many lines the user has entered to determine the number of names entered into the field. So I tried:
$i = 0;
$names = explode("\n", $userInput);
foreach($names as $name) {
$i++;
}
But this just gives me "1" as a result, regardless the number of new lines in the textarea. How do I make my explode count new lines instead of basing the count on something specifically entered into the text string?
EDIT Thanks to the people who answered, I don't believe there were any wrong answers as such, just one that suited my original code better than the others, and functioned. I ended up adopting this and modifying it so that numerous blank line returns did not result in artificially inflating the $userInput count. Here is what I am now using:
if(($userInput) != NULL) {
$i = 0;
$names = explode(PHP_EOL, trim($userInput));
foreach($names as $name) {
$i++;
}
}
It trims the empty space from the $userInput so that the remainder of the function is performed on only valid line content. :)

Don't make it complicated, you don't have to explode it into an array, just use this:
(Just count the new line character (PHP_EOL) in your string with substr_count())
echo substr_count($userInput, PHP_EOL);

Try using the PHP end of line constant PHP_EOL
$names = explode(PHP_EOL, $userInput);

A blank string as input:
var_dump(explode("\n", ''));
gives this as a result from a call to explode():
array(1) { [0]=> string(0) "" }
so you could use a ternary statement:
$names = $userInput == '' ? array() : explode("\n", $userInput);

Maybe you can change the explode function with preg_split to explode the user string with a regex
$users = preg_split('/[\n\r]+/', $original);
That's the idea, but I'm not on the computer so I can't test my code.
That regex would split the string if it founds one or more line breaks.

Related

PHP - Search, put letters written in bold

I'm trying to do a search engine where I write in a textbox, for example, "Mi" and it selects and shows "Mike Ross". However it's not working with spaces. I write "Mike" and I get "Mike Ross", but when I write "Mike " I get "Mike Ross" (no bold).
The same is happening with accents.
So I write "Jo" and the result is "João Carlos". If I write "Joa", the result is "João Carlos" (without any bold part). I want to ignore the accents while writing but still display them in the results.
So this is my script after the SELECT:
while($row = $result->fetch_array()) {
$name = $row['name'];
$array = explode(' ',trim($name));
$array_length = count($array);
for ($i=0; $i<$array_length; $i++ ) {
$letters = substr($array[$i], 0, $q_length);
if (strtoupper($letters) == strtoupper($q)) {
$bold_name = '<strong>'.$letters.'</strong>';
$final_name = preg_replace('~'.$letters.'~i', $bold_name, $array[$i], 1);
$array[$i] = $final_name;
}
array[$i] = array[$i]." ";
}
foreach ($array as $t_name) { echo $t_name;
}
Thank you for your help!
if (strtoupper($letters) == strtoupper($q))
This will never evaluate to "true" with spaces since you're removing spaces from the matchable letter set with explode(' ', trim($name), effectively making any value of $q with a space unmatchable to $letters
Here's a quick example that does what I think you're looking for
<?php
$q = "Mike "; // User query
$name = "Mike Ross"; // Database row value
if(stripos($name, $q) !== false) // Case-insensitive match
{
// Case-insensitive replace of match with match enclosed in strong tag
$result = preg_replace("/($q)/i", '<strong>$1</strong>', $name);
print_r($result);
}
// Result is
// <strong>Mike </strong>Ross
From what I can tell (a quick google for "replace accented characters PHP"), you're kind of out of luck with that one. This question provides a quick solution using strtr, and this tip uses a similar method with str_replace.
Unfortunately, these rely on predefined character sets, so incoming accents you haven't prepared for will fail. You may be better off relying on users to enter the special characters when they search, or create a new column with a "searchable" name with the accented characters replaced as best as you can, and return the real name as the "matched" display field.
One more Note
I found another solution that can do most of what you want, except the returned name will not have the accent. It will, however, match the accented value in the DB with a non-accented search. Modified code is:
<?php
$q = "Joa";
$name = "João Carlos";
$searchable_name = replace_accents($name);
if(stripos($searchable_name, $q) !== false)
{
$result = preg_replace("/($q)/i", '<strong>$1</strong>', $searchable_name);
print_r($result);
}
function replace_accents($str) {
$str = htmlentities($str, ENT_COMPAT, "UTF-8");
$str = preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde);/','$1',$str);
return html_entity_decode($str);
}

How to read integers separated by space from a file in php

I am trying to read a line where multiple numbers were separated by space using php. Initially I tried using fscanf however the issue is, as fscanf read one line at a time, it only reads the first number. I am confused what to do.
Sample Input
20 30 -5987 456 523
The best approach for this case is to use a combination of explode and file reading. The strategy is initially read the whole line as an string. Then use explode to store the all the number in an array. However in that case the array would a string array later on we can change the type of array element from String to integer. Here is how
<?php
$_fp = fopen("php://stdin", "r");
fscanf($_fp, "%d\n", $count);
$numbers = explode(" ", trim(fgets($_fp)));
foreach ($numbers as &$number)
{
$number = intval($number);
}
sort($numbers);
?>
$input = trim(fgets(STDIN));
$arr = explode(" ", $input);
foreach($arr as &$number){
$number = (int)$number;
}
If you want to eliminate white space from "fopen" function user "trim" function or surround variable with trim function.
Example :
echo "Please enter series limit : ";
$handles = fopen ("php://stdin","r");
$n = trim(fgets($handles));
So here we can remove white space in between the characters as well as at the end.

adding link values around each string

I have a php value coming back from my database as a string, like
"this, that, another, another"
And I'm trying to wrap a separate link around each of those strings, but I can't seem to get it to work. I've tried a for loop, but since it's just a string of information and not an array of information that doesn't really work. Is there a way to wrap a unique link around each value in my string?
The easiest way that I see to do this would be using PHP's explode() function. You'll find that it will become very useful as you start to use PHP more and more, so do check out its documentation page. It allows you to split a string up into an array given a certain separator. In your case, this would be ,. So to split the string:
$string = 'this, that, another, another 2';
$parts = explode(', ', $string);
Then use a foreach (again, check the documentation) to iterate through each of the parts and make them into a link:
foreach($parts as $part) {
echo '' . $part . "\n";
}
However, you can do this with a for loop. Strings can be accessed like arrays, so you can implement a parser pattern to parse the string, extract the parts, and create the links.
// Initialize some vars that we'll need
$str = "this, that, another, another";
$output = ""; // final output
$buffer = ""; // buffer to hold current part
// Iterate over each character
for($i = 0; $i < strlen($str); $i++) {
// If the character is our separator
if($str[$i] === ',') {
// We've reached the end of this part, so add it to our output
$output .= '' . trim($buffer) . "\n";
// clear it so we can start storing the next part
$buffer = "";
// and skip to the next character
continue;
}
// Otherwise, add the character to the buffer for the current part
$buffer .= $str[$i];
}
echo $output;
(Codepad Demo)
A better way is to do it like this
$string = "this, that, another, another";
$ex_string = explode(",",$string);
foreach($ex_string AS $item)
{
echo "<a href='#'>".$item."</a><br />";
}
First explode the string to get the individual words in an array. Then add the hyperlinks to the words and finally implode them.
$string = "this, that, another, another";
$words = explode(",", $string);
$words[0] = $words[0]
$words[1] = $words[1]
..
$string = implode(",", $words);
You can also use the for loop to assign hyperlinks that follow a pattern like this:
for ($i=0; $i<count($words); $i++) {
//assign URL for each word as its name or index
}

How line break content become one line paragraph?

*strong text*what i want to do is from my breakline content to one line paragraph
example my var_dump result:
string(212) "(73857,"2012-02-02 03:18:44","TXT",60143836234);"
string(122) "(73858,"2012-02-02 03:20:08","WAP",60143836234);"
string(211) "(73859,"2012-02-02 08:21:47","TXT",60163348563,);"
What i want to become:
string(555) "(73857,"2012-02-02 03:18:44","TXT",60143836234);(73858,"2012-02-02 03:20:08","WAP",60143836234);(73859,"2012-02-02 08:21:47","TXT",60163348563,);"
update (here is my code, $i is the line break records, if I able to make the breakline to one line, i will put in a new file )
foreach($get_line_feed_content as $i) {
$add_special_char = "(".$i.");";
var_dump($add_special_char);
if(!empty($i)){
$stringData = $final_content;
fwrite($save, $stringData);
fclose($save);
}
}
any idea?
Thank and highly appreciated your answer
Did you just want to glue the strings together? I don't see any line breaks from your dumps.
If that's the case, just do:
$finalString = $string1 . $string2 . $string3;
var_dump($finalString); //Strings should be glued as one.
If, however, each line is represented as an element in an array:
$stringsArray = array('string1', 'string2', 'string3');
$finalString = implode("", $stringsArray);
var_dump($finalString);
With your most recent update, this is what I would do:
$newString = '';
foreach($get_line_feed_content as $i) {
$newString .= "(".$i.");"; //concatenate
var_dump($newString); //You will get a lot of dumps and with each dump, a new string should be appended to it.
if(!empty($i)){
fwrite($save, $newString);
fclose($save);
}
}
if you want to glue strings you can do like this:
$data = $string1.$string2.$string3;
If you have array of strings do like this:
$strings = array('text1','text2','text3');
$data = implode('', $strings);

Slice sentences in a text and storing them in variables

I have some text inside $content var, like this:
$content = $page_data->post_content;
I need to slice the content somehow and extract the sentences, inserting each one inside it's own var.
Something like this:
$sentence1 = 'first sentence of the text';
$sentence2 = 'second sentence of the text';
and so on...
How can I do this?
PS
I am thinking of something like this, but I need somekind of loop for each sentence:
$match = null;
preg_match('/(.*?[?\.!]{1,3})/', $content, $match);
$sentence1 = $match[1];
$sentence2 = $match[2];
Ty:)
Do you need them in variables? Can't you use a array?
$sentence = explode(". ", $page_data->post_content);
EDIT:
If you need variables:
$allSentence = explode(". ", $page_data->post_content);
foreach($allSentence as $key => $val)
{
${"sentence". $key} = $val;
}
Assuming each sentence ends with full stop, you can use explode:
$content = $page_data->post_content;
$sentences = explode('.', $content);
Now your sentences can be accessed like:
echo $sentences[0]; // 1st sentence
echo $sentences[1]; // 2nd sentence
echo $sentences[2]; // 3rd sentence
// and so on
Note that you can count total sentences using count or sizeof:
echo count($sentences);
It is not a good idea to create a new variable for each sentence, imagine you might have long piece of text which would require to create that number of variables there by increasing memory usage. You can simply use array index $sentences[0], $sentences[1] and so on.
Assuming a sentence is delimited by terminating punctuation, optionally followed by a space, you can do the following to get the sentences in an array.
$sentences = preg_split('/[!?\.]\s?/', $content);
You may want to trim any additional spaces as well with
$sentences = array_map('trim', $sentences);
This way, $sentences[0] is the first, $sentences[1] is the second and so on. If you need to loop through them you can use foreach:
foreach($sentences as $sentence) {
// Do something with $sentence...
}
Don't use individually named variables like $sentence1, $sentence2 etc. Use an array.
$sentences = explode('.', $page_data->post_content);
This gives you an array of the "sentences" in the variable $page_data->post_content, where "sentences" really means sequences of characters between full stops. This logic will get tripped up wherever a full stop is used to mean something other than the end of a sentence (e.g. "Mr. Watson").
Edit: Of course, you can use more sophisticated logic to detect sentence boundaries, as you have suggested. You should still use an array, not create an unknown number of variables with numbers on the ends of their names.

Categories