I am trying to take a string like...
php,mysql,css
and turn it into .. #php #mysql #css
What I have so far...
$hashTagStr = "php,mysql,css";
$hashTags = explode(",", $hashTagStr);
foreach($hashTags as $k => $v){
$hashTagsStr = '';
$hashTagsStr .= '#'.$v.' ';
}
echo $hashTagsStr;
?>
Problem is it only prints #css
How about this:
$hashTagStr = "php,mysql,css";
$hashTags = explode(",", $hashTagStr);
$hashTagStr = '#' . implode( ' #', $hashTags );
...or:
$hashTagStr = "php,mysql,css";
$hashTagStr = '#' . str_replace( ',', ' #', $hashTagStr );
That's because every time the loop runs you're clearing out $hashTagsStr by doing:
$hashTagsStr = '';
Change it to:
$hashTagStr = "php,mysql,css";
$hashTags = explode(",", $hashTagStr);
$hashTagsStr = '';
foreach($hashTags as $k => $v){
$hashTagsStr .= '#'.$v.' ';
}
echo $hashTagsStr;
Pass your values by reference:
$hashTags = array("php","mysql","css");
foreach ( $hashTags as &$v ) $v = "#" . $v;
Then hammer out the results:
// #php #mysql #css
echo implode( " ", $hashTags );
Demo: http://codepad.org/zbtLF5Pk
Let's examine what you're doing:
// You start with a string, all good.
$hashTagStr = "php,mysql,css";
// Blow it apart into an array - awesome!
$hashTags = explode( "," , $hashTagStr );
// Yeah, let's cycle this badboy!
foreach($hashTags as $k => $v) {
// Iteration 1: Yeah, empty strings!
// Iteration 2: Yeah, empty...wait, OMG!
$hashTagsStr = '';
// Concat onto an empty var
$hashTagsStr .= '#'.$v.' ';
}
// Show our final output
echo $hashTagsStr;
looks like a Job for array_walk
$hashTagStr = "php,mysql,css";
$hashTags = explode(",", $hashTagStr);
array_walk($hashTags, function(&$value){ $value = "#" . $value ;} );
var_dump(implode(" ", $hashTags));
Output
string '#php #mysql #css' (length=16)
You should move the $hashTagsStr = '' line outsite the foreach loop, otherwise you reset it each time
You are defining the variable $hashTagsStrinside the loop.
<?php
$hashTagStr = "php,mysql,css";
$hashTags = explode(",", $hashTagStr);
$hashTagsStr = '';
foreach($hashTags as $k => $v){
$hashTagsStr .= '#'.$v.' ';
}
echo $hashTagsStr;
Anyway, I think this would be simpler:
<?php
$hashTagStr = "php,mysql,css";
$hashTagStr = '#' . str_replace(',', ' #', $hashTagStr);
echo $hashTagStr;
During each iteration of the loop, you are doing $hashTagsStr = '';. This is setting the variable to '', and then appending the current tag. So, when it's done, $hashTagsStr will only contain the last tag.
Also, a loop seems like too much work here, you can much easier just replace the , with #. No need to break it into an aray, no need to loop. Try this:
$hashTagStr = "php,mysql,css";
$hashTagStr = '#'.str_replace(',', ' #', $hashTagStr);
function prepend( $pre, $array )
{
return array_map(
function($t) use ($pre) { return $pre.$t; }, $array
);
}
What you semantically have in your string is an array. ➪ So better explode as soon as possible, and keep working with your array, as long as possible.
Closures & anonymous functions as shown work in PHP 5.4+.
Related
Let's say that I have the following string:
$string = 'xxyyzz';
And then I have a substitution array like this:
$subs = ['xy'];
Meaning that every x should be replaced by y in my string and every y should be replaced by x. Let's say that my substitution array can only contain pairs of characters to be replaced in my $string.
How would I go about doing this?
I tried using str_replace the following way but that doesn't work:
foreach ($subs as $sub) {
$sub_arr = str_split($sub);
$reversed_sub_arr = array_reverse($sub_arr);
$output = str_replace($sub_arr, $reversed_sub_arr, str_split($string));
}
$output = implode('', $output);
But the output gives me xxxxzz
The output should be yyxxzz
Thanks for any help
This working for your case
$string = 'xxyyzz';
$subs = ['xy'];
foreach ($subs as $sub) {
$sub_arr = str_split($sub);
$output = strtr($string, array($sub_arr[0]=>$sub_arr[1], $sub_arr[1]=>$sub_arr[0]));
}
echo $output; //yyxxzz
Extending #Orgil answer if two items in $subs array like $subs = ['xy', 'dz']
$string = $output = 'xxyyzz';
$subs = ['xy', 'dz'];
foreach ($subs as $sub) {
$sub_arr = str_split($sub);
$output = strtr($output, array($sub_arr[0]=>$sub_arr[1], $sub_arr[1]=>$sub_arr[0]));
}
echo $output;
Demo
I'm a newbie in PHP ,andnow I'm struck on this problem . I have a string like this :
$string = "qwe,asd,zxc,rty,fgh,vbn";
Now I want when user click to "qwe" it will remove "qwe," in $string
Ex:$string = "asd,zxc,rty,fgh,vbn";
Or remove "fhg,"
Ex:$string = "asd,zxc,rty,vbn";
I try to user str_replace but it just remove the string and still have a comma before the string like this:
$string = ",asd,zxc,rty,fgh,vbn";
Anyone can help? Thanks for reading
Try this out:
$break=explode(",",$string);
$new_array=array();
foreach($break as $newData)
{
if($newData!='qwe')
{
$new_array[]=$newData;
}
}
$newWord=implode(",",$new_array);
echo $newWord;
In order to achieve your objective, array is your best friend.
$string = "qwe,asd,zxc,rty,fgh,vbn";
$ExplodedString = explode( "," , $string ); //Explode them separated by comma
$itemToRemove = "asd";
foreach($ExplodedString as $key => $value){ //loop along the array
if( $itemToRemove == $value ){ //check if item to be removed exists in the array
unset($ExplodedString[$key]); //unset or remove is found
}
}
$NewLook = array_values($ExplodedString); //Re-index the array key
print_r($NewLook); //print the array content
$NewLookCombined = implode( "," , $NewLook);
print_r($NewLookCombined); //print the array content after combined back
here the solution
$string = "qwe,asd,zxc,rty,fgh,vbn";
$clickword = "vbn";
$exp = explode(",", $string);
$imp = implode(" ", $exp);
if(stripos($imp, $clickword) !== false) {
$var = str_replace($clickword," ", $imp);
}
$str = preg_replace('/\s\s+/',' ', $var);
$newexp = explode(" ", trim($str));
$newimp = implode(",", $newexp);
echo $newimp;
You could try preg_replace http://uk3.php.net/manual/en/function.preg-replace.php if you have the module set up. It will allow you to optionally replace trailing or leading commas easily:
preg_replace("/,*$providedString,*/i", '', "qwe,asd,zxc,rty,fgh,vbn");
I'm using a javascript plugin this is the line which I need help from u
<script type="text/javascript">
$('ul#news').newswidget({ source: ['http://rss.news.yahoo.com/rss/us', 'http://rss.news.yahoo.com/rss/world', 'http://feeds.bbci.co.uk/news/rss.xml'],
I would like to add URL data from MySQL
I'm using it with while loop like this
$('ul#news').newswidget({ source:[<?php
while($rssrow = mysql_fetch_array($rss))
{
echo "'"."$rssrow[rss_name]"."'".",";
}
?>],
It doesn't work properly :(.
I need to get like URL,URL,RUL like this.
that means no comma for the last one
any one please help me
You can actually do that pretty easily by a simple reorganization:
if($rssrow = mysql_fetch_array($rss))
{
echo "'".$rssrow['rss_name']."'";
while($rssrow = mysql_fetch_array($rss))
{
// note no quotes -- they are redundant
// prepend the comma
echo ","."'".$rssrow['rss_name']."'";
}
}
It does make for an extra step for the reader, but it does have the benefit of not needing substring, a new array, or a flag.
You could just build the string and remove the last comma:
$result = '';
while($rssrow = mysql_fetch_array($rss))
{
$result .= "'"."$rssrow[rss_name]"."'".",";
}
echo ($result != '') ? substr($result, 0, -1) : "''";
OR use implode():
$result = array();
while($rssrow = mysql_fetch_array($rss))
{
$result[] = $rssrow[rss_name];
}
echo "'" . implode($result, "','") . "'";
(both of these methods will output '' if the result set is empty.)
$urls = "";
while($rssrow = mysql_fetch_array($rss))
{
$urls.= "'$rssrow[rss_name]',";
}
echo substr($urls, 0, -1);
I wonder why no comment points out that you should definitely escape your output. If an entry contains a ', all solutions aside from Dmitry F’s first will break badly.
$('ul#news').newswidget({ source:[<?php
$arr = array();
while($rssrow = mysql_fetch_array($rss))
{
$arr[] = '"' . str_replace('"', '\"', $rssrow['rss_name']) . '"';
}
echo implode(',', $arr);
?>],
here is a little bit different approach:
<?php
$news = array(
'source' => array(
'http://example.com',
'http://example.com'
)
);
$news_json = json_encode($news);
?>
<script>
$('ul#news').newswidget(<?php echo $news_json; ?>);
</script>
another variation:
$url = array();
while($rssrow = mysql_fetch_array($rss))
{
$url[] = '"' . $rssrow['rss_name'] . '"';
}
echo implode(',', $url);
I have a comma separated string, which consists of a list of tags and want to convert it to array to get a link for every tag.
Example:
$string = 'html,css,php,mysql,javascript';
I want to make it like this:
html, css, php, mysql, javascript
So the result will be a string containing comma separated links with a space after each link and with no comma after the last link.
I have this function where $arg = 'html,css,php,mysql,javascript':
function info_get_tags( $arg ) {
global $u;
$tagss = '';
if ( $arg == '' ) {
return '';
} else {
$tags_arr = explode( ',' , $arg );
foreach ( $tags_arr as $tag ) {
$tags = '' . $tag . '';
$tagss .= $tags;
}
return $tagss;
}
}
This script works for me but without commas and spaces and if we add a comma and a space here:
$tags = '' . $tag . ', ';
we get commas and spaces but there will be a trailing comma after the last link.
Just like you exploded you can implode again:
$tags = explode(',', $arg);
foreach ($tags as &$tag) {
$tag = '' . $tag . '';
}
return implode(', ', $tags);
Here's an alternative that uses array_map instead of the foreach loop:
global $u;
function add_html($tag){
return('' . $tag . '');
}
function get_tags($taglist){
$tags_arr = array_map("add_html", explode( ',' , $taglist));
return implode(", " , $tags_arr);
}
Try this short code
$string = 'html,css,php,mysql,javascript';
$string = explode(',', $string);
foreach( $string as $link){
echo ''.$link.'';
}
Easiest way is to the html into an array (each tag link is an array element) and then implode on ,...
if ( $arg == '' ) {
return '';
} else {
$tags_arr = explode( ',' , $arg );
$tags = array();
$tagtpl = '%s';
foreach ( $tags_arr as $tag ) {
$url = $u . 'tag/' . $tag . '/';
$tags[] = sprintf($tagtpl, $url, $tag, $tag);
}
return implode(', ', $tags);
}
Try this
$tagss = trim($tagss);
return substr($tagss, 0 , strlen($tagss)-1);
Why not put all tags in an array when you are creating them, and later explode the array and add the commas and spaces between the tags.
foreach ( $tags_arr as $tag ) {
$tags = '' . $tag . '';
$tagss[] = $tags;
}
$tagss = explode(', ', $tagss);
The workaround(!) would be to remove the unwanted trailing characters afterwards:
$tagss = rtrim($tagss, ", ");
This rtrim removes any mix of spaces and commas from the right end of the string.
Btw, you could use str_getcsv instead of explode, which also handles input spaces better.
function info_get_tags($arg)
{
global $u;
if (empty($arg)) return '';
return ltrim(preg_replace('/([^\,]+)/', ' ${1}', $arg));
}
$string = 'html,css,php,mysql,javascript';
puts $string.split(/,/).map { |tag| "#{tag}"}.join(", ")
result:
html, css, php, mysql, javascript
Another solution:
$html = trim(preg_replace('/([^,]+)/', ' \1', $string));
Or if you have to html encode the tags (always smart, since you're creating html from text):
$html = trim(preg_replace_callback('/([^,]+)/', function($match) {
$tag = $match[1];
return ' ' . htmlspecialchars($tag) . '';
}, $string));
So this $string would work too: "tag with space,html,css,php,mysql,javascript"
More regex is always good!
I have an array, which I am using the following code:
foreach ($taglist as $tag=>$size){
echo link_to(
$tag,
"#search-tag?tag=" . strtolower($tag),
array(
"class" => 'tag' . $size,
"title" => "View all articles tagged '" . $tag . "'"
)
);
}
Now, this simply prints a hyperlink
What I'm looking to do, is to add the pipe char ( | ) after every link, apart from the last one.
Could I do this in a loop?
Thanks
$k = 0;
foreach($taglist as $tag=>$size)
{
$k++;
echo link_to($tage, ...);
if ($k != sizeof($taglist)) echo '|';
}
You can use a plain old boolean variable:
$first = true;
foreach($taglist as $tag=>$size){
if ($first) $first = false; else echo '|';
echo link_to($tage, ...);
}
Note that technically, this code outputs a bar before every element except the first, which has the exact same effect as outputting a bar after every element except the last.
Use a temporary array then join elements /
$links = array();
foreach($taglist as $tag=>$size){
$links[] = link_to($tag, ...);
}
echo implode('|', $links);
You can use a CachingIterator
$links = new CachingIterator(new ArrayIterator($tagList));
foreach($links as $tag => $size) {
echo link_to(/* bla */), $links->hasNext() ? '|' : '';
}
For more info on the CachingIterator see my answer at Peek ahead when iterating an array in PHP