this is a problem I keep running into, and would like to know the best way to do this.
I'm trying to split each value in this array into an individual string,
$domainext = array("com","net","edu","uk","au","in","biz","ca","cc","cd","bz","by");
Here is how I'm doing it.
foreach ($domainext as $ext){
$ext = implode(', ', $domainext);
echo $ext."<br>";
echo "<br>";
}
this is the output.
com, net, edu, uk, au, in, biz, ca, cc, cd, bz, by
(however, there are as many lines as there are array values)
I have tried using explode, and it returns "array" with an error above it.
Any help would be greatly appreciated, and sorry for such a basic question.
I think this is what you are looking for:
$domainext = array("com","net","edu","uk","au","in","biz","ca","cc","cd","bz","by");
print implode("\n", $domainext);
This gives:
com
net
edu
....
Oops... replace the "\n" by a br tag if you are printing to a web page.
print implode("<br/>", $domainext);
You dont need to implode or explode anything :), try this:
foreach ($domainext as $ext){
echo $ext."<br>";
echo "<br>";
}
If you just want to output the items in your array on a different row, you cna use join
echo join("<br/>",$domainext);
As others have said, no loop necessary.
Simply:
echo join('<br>', $domainext);
will do the job if you want each domain suffix separated with HTML line breaks (the exact required output is unclear from your question). Join is an alias of implode, and preferable from its clearer meaning.
Related
I'm trying to use SimplePies "$feed->set_feed_url (array());" function but I am having major difficulty understanding why it wont accept my values.
When I add the URLS manually (i.e directly below), they work just fine. The feeds go through ok and displays the feeds as needed.
$feed ->set_feed_url (array(
'http://www.theverge.com/tag/rss',
'http://feeds.ign.com/ign/all'
));
I have URLS in a database table that I am pulling out like normal with a while loop. I then append a comma and remove the trailing comma so its nice for the SimplePie array. Like so:
while($row = mysqli_fetch_array($pullAllAccountsDoIt)){
$result4mdb .= $row[0] . ",";
}
$result4mdb = substr($result4mdb, 0, strlen($result4mdb) -1);
echo "the result is: " . $result4mdb;
When I do this, and echo out "$result4mdb", it prints out: the result is: http://www.gamespot.com/feeds/mashup/,http://www.theverge.com/tag/rss
Meaning that the variable is good and printing out what i need. So far so good.
I then go into the simplePie code, put in my varialble like so:
$feed ->set_feed_url (array($result4mdb));
and nothing happens. I don't get any errors or anything, just that the page stays blank and nothing comes up.
For testing, I do a gettype($result4mdb); and it tells me that the variable is a "string" and again, the output of this variable when echoed is the URLS it got from the database so I KNOW that the whole process so far is working.
For further testing, I go to the database and remove one of the URLS so that when queried, that it returns one value, and all of the sudden SimplePie works.
I've been searching for a good day and a half now, trying different things and googling as much as possible but to no avail. I just cant quite get it.
I'm at my wits end. Any assistance as to why this isn't working is GREATLY appreciated.
Thank you in advance everyone
You're just producing a string containing comma seperated values. What you need is an array, so just explode() your string:
Change:
$feed ->set_feed_url (array($result4mdb));
to
$feed ->set_feed_url (explode(',', $result4mdb));
More elegant version, change:
while($row = mysqli_fetch_array($pullAllAccountsDoIt)){
$result4mdb .= $row[0] . ",";
}
to
while($row = mysqli_fetch_array($pullAllAccountsDoIt)){
$result4mdb[] = $row[0];
}
This way you're not creating a string that needs to be exploeded, but create an array at first.
I'm currently trying out this PHP preg_replace function and I've run into a small problem. I want to replace all the tags with a div with an ID, unique for every div, so I thought I would add it into a for loop. But in some strange way, it only do the first line and gives it an ID of 49, which is the last ID they can get. Here's my code:
$res = mysqli_query($mysqli, "SELECT * FROM song WHERE id = 1");
$row = mysqli_fetch_assoc($res);
mysqli_set_charset("utf8");
$lyric = $row['lyric'];
$lyricHTML = nl2br($lyric);
$lines_arr = preg_split('[<br />]',$lyricHTML);
$lines = count($lines_arr);
for($i = 0; $i < $lines; $i++) {
$string = preg_replace(']<br />]', '</h4><h4 id="no'.$i.'">', $lyricHTML, 1);
echo $i;
}
echo '<h4>';
echo $string;
echo '</h4>';
How it works is that I have a large amount of text in my database, and when I add it into the lyric variable, it's just plain text. But when I nl2br it, it gets after every line, which I use here. I get the number of by using the little "lines_arr" method as you can see, and then basically iterate in a for loop.
The only problem is that it only outputs on the first line and gives that an ID of 49. When I move it outside the for loop and removes the limit, it works and all lines gets an <h4> around them, but then I don't get the unique ID I need.
This is some text I pulled out from the database
Mama called about the paper turns out they wrote about me
Now my broken heart´s the only thing that's broke about me
So many people should have seen what we got going on
I only wanna put my heart and my life in songs
Writing about the pain I felt with my daddy gone
About the emptiness I felt when I sat alone
About the happiness I feel when I sing it loud
He should have heard the noise we made with the happy crowd
Did my Gran Daddy know he taught me what a poem was
How you can use a sentence or just a simple pause
What will I say when my kids ask me who my daddy was
I thought about it for a while and I'm at a loss
Knowing that I´m gonna live my whole life without him
I found out a lot of things I never knew about him
All I know is that I´ll never really be alone
Cause we gotta lot of love and a happy home
And my goal is to give every line an <h4 id="no1">TEXT</h4> for example, and the number after no, like no1 or no4 should be incremented every iteration, that's why I chose a for-loop.
Looks like you need to escape your regexp
preg_replace('/\[<br \/\]/', ...);
Really though, this is a classic XY Problem. Instead of asking us how to fix your solution, you should ask us how to solve your problem.
Show us some example text in the database and then show us how you would like it to be formatted. It's very likely there's a better way.
I would use array_walk for this. ideone demo here
$lines = preg_split("/[\r\n]+/", $row['lyric']);
array_walk($lines, function(&$line, $idx) {
$line = sprintf("<h4 id='no%d'>%s</h4>", $idx+1, $line);
});
echo implode("\n", $lines);
Output
<h4 id="no1">Mama called about the paper turns out they wrote about me</h4>
<h4 id="no2">Now my broken heart's the only thing that's broke about me</h4>
<h4 id="no3">So many people should have seen what we got going on</h4>
...
<h4 id="no16">Cause we gotta lot of love and a happy home</h4>
Explanation of solution
nl2br doesn't really help us here. It converts \n to <br /> but then we'd just end up splitting the string on the br. We might as well split using \n to start with. I'm going to use /[\r\n]+/ because it splits one or more \r, \n, and \r\n.
$lines = preg_split("/[\r\n]+/", $row['lyric']);
Now we have an array of strings, each containing one line of lyrics. But we want to wrap each string in an <h4 id="noX">...</h4> where X is the number of the line.
Ordinarily we would use array_map for this, but the array_map callback does not receive an index argument. Instead we will use array_walk which does receive the index.
One more note about this line, is the use of &$line as the callback parameter. This allows us to alter the contents of the $line and have it "saved" in our original $lyrics array. (See the Example #1 in the PHP docs to compare the difference).
array_walk($lines, function(&$line, $idx) {
Here's where the h4 comes in. I use sprintf for formatting HTML strings because I think they are more readable. And it allows you to control how the arguments are output without adding a bunch of view logic in the "template".
Here's the world's tiniest template: '<h4 id="no%d">%s</h4>'. It has two inputs, %d and %s. The first will be output as a number (our line number), and the second will be output as a string (our lyrics).
$line = sprintf('<h4 id="no%d">%s</h4>', $idx+1, $line);
Close the array_walk callback function
});
Now $lines is an array of our newly-formatted lyrics. Let's output the lyrics by separating each line with a \n.
echo implode("\n", $lines);
Done!
If your text in db is in every line why just not explode it with \n character?
Always try to find a solution without using preg set of functions, because they are heavy memory consumers:
I would go lke this:
$lyric = $row['lyric'];
$lyrics =explode("\n",$lyrics);
$lyricsHtml=null;
$i=0;
foreach($lyrics as $val){
$i++;
$lyricsHtml[] = '<h4 id="no'.$i.'">'.$val.'</h4>';
}
$lyricsHtml = implode("\n",$lyricsHtml);
An other way with preg_replace_callback:
$id = 0;
$lyric = preg_replace_callback('~(^)|$~m',
function ($m) use (&$id) {
return (isset($m[1])) ? '<h4 id="no' . ++$id . '">' : '</h4>'; },
$lyric);
I use the following code to add a comma , at the end of every filename. After this using explode i put the rows on an array.
The images array if I echo it, it shows a.jpg,b.jpg,c.jpg, (please mind the last comma at the end of c.jpg)
How can I avoid adding a comma to the last found row?
<?php
while($image = mysql_fetch_array($images)) {
$images_path .= $image['FILE_NAME'].',';
}
$images_array = explode(",", $images_path);
?>
Make use of rtrim() by providing a comma as the second paramter as character mask
$images_path = rtrim($images_path,","); //<---- The added code
$images_array = explode(",", $images_path);
Why add it to a string and then convert it to an array, if you can add it straight away?
$images_array = array();
while($image = mysql_fetch_array($images)) {
$images_array[] = $image['FILE_NAME'];
}
You do this:
Create your required string
Knowingly introduce a problem that can easily be avoided
Fix the issue you created with more code (generate your required array by splitting the string)
Instead, do this:
Create the required array as you want it, first time
Your current approach will create more problems as your coding style improves, and you have more complex code and are reusing your code (ie this would be in a class).
Like this:
<?php
while($image = mysql_fetch_array($images))
{
$images_array[] = $image['FILE_NAME'];
}
?>
Instead of, how you currently do it, setting a variable with the data from the database, with a comma separating each value (and a rouge one at the end as a result), then exploding the variable into an array, and wanting to remove the end comma..
Just set the array in the first place!
The simplest way from the code you supplied would be
explode(',', $images_path, -1);
in most cases you might reconsider if you really need a string which has been constructed in such a way.
There are going to be a dozen ways to tackle this, some pretty, some not.
Ideally, this is why you use libraries like Apache / Google commons in production code, so that there is standard ways to do things like implode / explode ; split / join; or whatever its called in the language you are in.
With that said, maybe you are writing base code or provide this as a library or maybe just want to know how you handle this.
I don't care for the trim options, they are destructive and you will find yourself one day when you depend upon things of that nature, staring at a code review or debugging a problem and thinking, oh this trim, substring whatever is making assumptions and messing things up, which when in base / shared code is bad to be making.
I would handle this in a more deterministic way of:
(pseudocode)
<?php
$images_path = "";
// Base case
if($image = mysql_fetch_array($images)) {
$images_path .= $image['FILE_NAME'];
}
// If multiple results, iterate
while($image = mysql_fetch_array($images)) {
$images_path .= ',' . $image['FILE_NAME'];
}
$images_array = explode(",", $images_path);
?>
Switch it from appending the , to prepending the comma when there are multiple. Now you never have to remove an extra comma or do any destructive command. Very similar how doing a proof you build a base case and then build on the base.
I need some assistance with php. I have been trying several things for the past several days including str_replace to no avail.
I have a field that may contain from 1 to 20 values, all listed on their own line, there is no html code in that field to separate them and some of the values may have their own spaces in between, so separating by space doesnt work.
What I need is to extract every single string of each line and convert it to code.
<p>For example, my field with values looks like this: </p>
<p><b>lang_fld </b><br>
------
<br>
English<br>
Spanish<br>
German<br>
French</p>
What I have in mind is to extract each line, ex. "English" from that string, and create a line of code like
<img src="images/flags/english.png> English
Basically I want to add the flag graphic to the word
I already tried
echo str_replace('English','<img src="images/flags/english.png>,lang_fld)<br>
...and so on
what I get after going through every single possible value is a bunch error
messages (different every time since I keep making changes - by guessing)
Can someone offer an easier option to do this? Not all 20 values will be in
that areatext field, some may contain just one language, some ten, some all 20,
etc.
Thank you!
Assuming you have all the values on a separate line, you can do explode() on the string to convert it to array of separate items, then loop through the array with foreach and perform any modifications with the single item. After you are done with the items and you would like to get them back together, you can use implode() to combine them into a single string.
A short sample ( you can of course use a for loop, I just prefer foreach here as it shows you better what is happening with the data ):
$text =
"French language
Italian language
English language";
$items = explode( "\n", $text ); // Split by newline ( you can also use "<br>" as separator )
$result = array(); // Modified data will be placed here
foreach ( $items as $item )
{
// Do something with $item
$item = "<img src=\"images/flags/$item.png\"> $item";
$result[] = $item;
}
// Merge them back together
$text = implode("\n", $result);
I have correctly created an array and have an array item with:
$array[2] = "Automotive Repairs and Servicing";
I try to do a search on $array for Automotive Repairs and Servicing and it returns false:
array_search('Automotive Repairs and Servicing', $array);
I found that it returns false because I have a space within the search string, i.e. Automotive(space)Repairs(space)and(space)Servicing.
Does anyone know how I can make my search successfully return the key?
I have tried with space as %20, \n, and as follows:
array_search('Automotive%20Repairs%20and%20Servicing', $array);
array_search('Automotive\nRepairs\nand\nServicing', $array);
array_search('Automotive Repairs and Servicing', $array);
I will continue to try and fix this problem and if I solve it I will post my answer.
...Thank you for your answer below. I tried your code and it worked for me too.
My real array is actually constructed of data from a database using mysql query and putting the result straight into the array. So not quite sure where the problem lies now.
...
My Answer:
Thank you all for responding and helping me with this problem.
I have found my problem... and I'm extremely embarrassed.
Turns out there was a space that I didn't see at the end of the string 'Automotive Repairs and Servicing ' in my database.
I've struck this before, my mysql database just like to mess with my head like this sometimes.
So for anyone else out there that gets their mysql result and sticks it into an array then strikes similar problems to this, make sure that your mysql isn't 'pranking' you with a space (invisible to the human eye) in your data.
I'm going out for a cigarette.
I'm really seeing no issue in that...
But here's exactly what I tried :
<?php
$array[0] = "noo";
$array[1] = "DONE";
$array[2] = "Automotive Repairs and Servicing";
$index = array_search('Automotive Repairs and Servicing', $array);
echo "Index = $index";
?>
And here's the output :
Index = 2