Loop through condition and append to string in php? [duplicate] - php

This question already has answers here:
concat a for loop - php
(3 answers)
Closed 2 years ago.
Am writing some content to a file, I store all the content in a variable. Some parts of the file content need to be repeated with some minor changes, those changes are stored in a variable and I need to run a for loop for that change.
See the following code sample,
$looped_valueArray; //this is an array i need to loop the content in $looped_value
//to show all the values
$content = 'sample content '. $looped_value.'
fdgdf';
I could not loop write a forloop appending to a string like
$content = 'sample content '.
foreach($looped_valueArray as $looped_value) $looped_value;.'fdgdf';

Hi follow this scripts if you would like append your content in a variable:
$content ="sample content ";
foreach($looped_valueArray as $looped_value){
$content .=$looped_value;
}

You can't use a loop directly in the string. Either define a separate function that loops through the values, or, in the above example, you could just use implode():
$content = 'sample content ' . implode("", $looped_valueArray) . 'fdgdf';

Related

PHP replace text inside specific text [duplicate]

This question already has answers here:
Parse Wordpress like Shortcode
(7 answers)
Closed 4 years ago.
I'm using str_replace to replace a simple shortcode which works fine:
$content = "[old_shortcode]";
$old_shortcode = "[old_shortcode]";
$new_shortcode = "[new_shortcode]";
echo str_replace($old_shortcode, $new_shortcode, $content);
However I want to also replace attributes inside the shortcode without affecting any text content, for example change this:
[old_shortcode old_option_1="Text Content" old_option_2="Text Content"]
To this:
[new_shortcode new_option_1="Text Content" new_option_2="Text Content"]
Much appreciated if anyone could advise on how to do this.
To clarify, this question is not about parsing a shortcode (as it has been marked as a duplicated), it's about replacing one shortcode with another which the duplicate question linked to does not answer.
Edit:
I figured it out myself, however it's probably not a very elagant solution if anyone wants to suggest something better?
$pattern1 = '#\[shortcode(.*)attribute1="([^"]*)"(.*)\]#i';
$replace1 = '[shortcode$1attribute1_new="$2"$3]';
$pattern2 = '#\[shortcode(.*)attribute2="([^"]*)"(.*)\]#i';
$replace2 = '[shortcode$1attribute2_new="$2"$3]';
$pattern3 = '#\[shortcode(.*)(.*?)\[/shortcode\]#i';
$replace3 = '[new_shortcode$1[/new_shortcode]';
$content = '[shortcode attribute2="yes" attribute1="whatever"]Test[/shortcode]';
echo preg_replace(array($pattern1,$pattern2,$pattern3), array($replace1,$replace2,$replace3), $content);
Use preg_replace() instead that select only part of string you want using regex.
$newContent = preg_replace("/[a-zA-Z]+(_[^\s]+)/", "new$1", $content);
Check result in demo

Insert php code inside sendgrid mail content html [duplicate]

This question already has an answer here:
Output code as text in php
(1 answer)
Closed 4 years ago.
I am using Sendgrid to send an email via PHP but I need to include a PHP script in the HTML content. I do not know how to perform the concatenation, it seems really delicate.
Here's my code:
$content = new SendGrid\Content("text/html", '
/*
some HTML content
*/
/*PHP script starts here*/
'.myPHP Script {
}//end of script
.'
/*some more HTML content
');
The '..' concatenation does not work and the entire page fails to load. How do I go about this? I am not trying to output the code. I want it to actually execute.
Don't make life difficult. What ever string you need to concat, put it in a variable and concat that. also note you can do string interpolation in PHP using the double quotes "$variable".
$concatHTML = '';
$prodList = [...]; // assume we have products list here
for ($i = 0, $max = count($prodList); $i < $max; $i++) {
$concatHTML += '<div>'. $prodList[$i] .'</div>';
}
$content = new SendGrid\Content("text/html", "
//some html content here
$concatHTML
");
EDIT
Concatenation could be done using the operator . (e.g.) echo 'hi ' . $name; where $name = 'some string' or using string string interpolation using double quotes and and placing (e.g.) echo "hi $name" you can add curly braces to make separate the variable from the other string like echo "hi Mr.{$name}".
For the php code you want to include in the email is probably not valid.

Trying to grab value from html page but getting template back not the value - php

I am making a price crawler for a project but am running into a bit of an issue. I am using the below code to extract values from an html page:
$content = file_get_contents($_POST['url']);
$resultsArray = array();
$sqlresult = array();
$priceElement = explode( '<div>value I want to extract</div>' , $content );
Now when I use this to get certain elements I only get back
Finance: {{value * value2}}
I want to get the actual value that would be displayed on the screen e.g
Finance: 7.96
The other php methods I have tried are:
curl
file_get_html(using simple_html_dom library)
None of these work either :( Any ideas what I can do?
You just set the <div>value I want to extract</div> as a delimiter, which means PHP looks for it to separate your string to array whenever this occurs.
In the following code we use , character as a delimiter:
<?php
$string = "apple,banana,lemon";
$array = explode(',', $string);
echo $array[1];
?>
The output should be this:
banana
In your example you set the value you want to extract as a delimiter. That's why this happens to you. You'll need to set a delimiter between your string you want to obtain and other string you won't need at the moment.
For example:
<?php
$string = "iDontNeedThis-dontExtractNow-value I want to extract-dontNeedEither";
$priceElement = explode('-', $string);
echo "<div>".$priceElement[2]."</div>";
?>
The code should output this to your HTML page:
<div>value I want to extract</div>
And it will appear on your page like this:
value I want to extract
If you don't need to save the whole array in a variable, you can save the one index of it to variable instead:
$priceElement = explode('-', $string)[2];
echo $priceElement;
This will save only value I want to extract so you won't have to deal with arrays later on.

Additional elements to URLS?

I'm not sure what the terminology is, but basically I have a site that uses the "tag-it" system, currently you can click on the tags and it takes the user to
topics.php?tags=example
My question is what sort of scripting or coding would be required to be able to add additional links?
topics.php?tags=example&tags=example2
or
topics.php?tags=example+example2
Here is the code in how my site is linked to tags.
header("Location: topics.php?tags={$t}");
or
<?php echo strtolower($fetch_name->tags);?>
Thanks for any hints or tips.
You cannot really pass tags two times as a GET parameter although you can pass it as an array
topics.php?tags[]=example&tags[]=example2
Assuming this is what you want try
$string = "topics.php?";
foreach($tags as $t)
{
$string .= "tag[]=$t&";
}
$string = substr($string, 0, -1);
We iterate through the array concatenating value to our $string. The last line removes an extra & symbol that will appear after the last iteration
There is also another option that looks a bit more dirty but might be better depending on your needs
$string = "topics.php?tag[]=" . implode($tags, "&tag[]=");
Note Just make sure the tags array is not empty
topics.php?tags=example&tags=example2
will break in the back end;
you have to assign the data to one variable:
topics.php?tags=example+example2
looks good you can access it in the back end explode it by the + sign:
//toplics.php
<?php
...
$tags = urlencode($_GET['tags']);
$tags_arr = explode('+', $tags); // array of all tags
$current_tags = ""; //make this accessible in the view;
if($tags){
$current_tags = $tags ."+";
}
//show your data
?>
Edit:
you can create the fron-end tags:
<a href="topics.php?tags=<?php echo $current_tags ;?>horror">
horror
</a>

Get rid of last comma [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Removing last comma in PHP?
Remove the last Comma from a string (PHP / Wordpress)
I have code which from some reason is not working. What I am trying to do is get rid of last comma from the result but it won't work. Here is the code
<?php do {
$activity_user_first_name = $row_product_activity['user_first_name'];
$activity_user_last_name = $row_product_activity['user_last_name'];
$name = ''.$activity_user_first_name.' '.$activity_user_last_name.', ';
echo rtrim($name, ",");
} while($row_product_activity = mysql_fetch_assoc($product_activity)) ?> like this
So the results I want to get is this
Steve Jobs, Bill Gates, Sergey Brin, Larry Page like this
instead I get this
Steve Jobs, Bill Gates, Sergey Brin, Larry Page, like this
so I want that comma after Larry Page or any other name that is at the end be deleted. I tried playing around with many other options but the nothing came up as I wish. Any suggestions would be appreciated.
I think a better solution is to construct the string without the trailing comma in the first place. Put the links for each name into an array slot and then just echo some imploded results.
<?php
$names=array();
do {
$activity_user_first_name = $row_product_activity['user_first_name'];
$activity_user_last_name = $row_product_activity['user_last_name'];
$names[] = ''.$activity_user_first_name.' '.$activity_user_last_name.'';
} while($row_product_activity = mysql_fetch_assoc($product_activity));
echo implode(', ', $names);
?> Like This

Categories