How do I convert a PHP foreach output into a string? - php

function Foo($word) {
$lowerword= strtolower($word);
$words = explode(" ", $lowerword);
foreach ($words as $wrd){
echo $wrd[0];
}
}
$word = "my name is";
$firstletters = Foo($word);
Source code above. The idea is to take the first letter from each word in a sentence and piece them together as one string that can then be further manipulated. However, I am having difficulty manipulating the output, making me think that the output is not really one string. How do I convert the output of the foreach loop into a string?

The output is not a string at all indeed. Your function does echo but doesn't return anything.
Try this function:
function Foo($word) {
$lowerword= strtolower($word);
$words = explode(" ", $lowerword);
$firstLetters = '';
foreach ($words as $wrd){
$firstLetters .= $wrd[0];
}
return $firstLetters;
}

Related

multiple characters replacements in string php

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

PHP - Exploding each item in an array created by explode

My code is...
$string ="foo:bar,bar,bar|foo2:bar2,bar2,bar2";
$first_array = explode("|", $string);
function split(&$block) {
$block = explode(":", $block);
}
array_walk($first_array, "split");
echo $block["0"]["0"];
echo "<br />";
echo $block["0"]["1"];
?>
Thank you for the help thus far. From what I've gathered this should be the clean version of the supplied code. This does not echo anything, and neither does the code supplied.
This will do the trick:
$string ="foo:bar:bar:bar|foo2:bar2:bar2:bar2";
// first explode on |
$first_array = explode("|", $string);
// this function go on each lines of an array and transform each by a function
array_walk($first_array, function(&$item) {
// so for each line explode with ':' as delimiter
$item = explode(':', $item);
});
// To check all lines of the array
foreach($first_array as $line_array) {
//my code for each sub-array
}
// To get only the last (second)
$second_sub = array_pop($first_array);
// if you want one dimension with all exploded you can use
// this function split with a regexp pattern
// "/[\|:,]+/" foreach "|" or ":" or "," split the string
preg_split("/[\|:,]+/", $string);
Don't use $block since it's defined in another scope, moreover you cannot give "split" as a name for your function since it's an existing php function
$string ="foo:bar,bar,bar|foo2:bar2,bar2,bar2";
$first_array = explode("|", $string);
function mysplit(&$block) {
$block = explode(":", $block);
}
array_walk($first_array, "mysplit");
echo $first_array[0][0];
echo "<br />";
echo $first_array[0][1];

PHP Extract each occurrence of an item within a string

In the event of a string that says:
Once upon a time a small young LKTgoblingLKT had an unfortunate accident and LKTfellLKT.
How could I extract each occurrence of content contained within LKT into an array and replace them in the string.
You can try the following solution:
Store the sentence in a variable
explode() the sentence with space as the delimiter
Loop through the array
Check if the word contains your string using strpos()
If it does, push the word into the result array
Something like this:
$string = '...';
$words = explode(' ', $string);
foreach ($words as $word) {
if (strpos($word, 'LKT') !== FALSE) {
$result[] = $word;
}
}
print_r($result);
Output:
Array
(
[0] => LKTgoblingLKT
[1] => LKTfellLKT.
)
Demo!
If you want the string to be replaced with another word, you can use str_replace() and implode(), like so:
$string = '...';
$words = explode(' ', $string);
$result = array();
foreach ($words as $word) {
if (strpos($word, 'LKT') !== FALSE) {
$word = str_replace($word, 'FOO', $word);
}
$result[] = $word;
}
$resultString = implode(' ', $result);
echo $resultString;
Output:
Once upon a time a small young FOO had an unfortunate accident and FOO
Demo!

Extracting Twitter hashtag from string in PHP

I need some help with twitter hashtag, I need to extract a certain hashtag as string variable in PHP.
Until now I have this
$hash = preg_replace ("/#(\\w+)/", "#$1", $tweet_text);
but this just transforms hashtag_string into link
Use preg_match() to identify the hash and capture it to a variable, like so:
$string = 'Tweet #hashtag';
preg_match("/#(\\w+)/", $string, $matches);
$hash = $matches[1];
var_dump( $hash); // Outputs 'hashtag'
Demo
I think this function will help you:
echo get_hashtags($string);
function get_hashtags($string, $str = 1) {
preg_match_all('/#(\w+)/',$string,$matches);
$i = 0;
if ($str) {
foreach ($matches[1] as $match) {
$count = count($matches[1]);
$keywords .= "$match";
$i++;
if ($count > $i) $keywords .= ", ";
}
} else {
foreach ($matches[1] as $match) {
$keyword[] = $match;
}
$keywords = $keyword;
}
return $keywords;
}
As i understand you are saying that
in text/pargraph/post you want to show tag with hash sign(#) like this:- #tag
and in url you want to remove # sign because the string after # is not sended to server in request so i have edited your code and try out this:-
$string="www.funnenjoy.com is best #SocialNetworking #website";
$text=preg_replace('/#(\\w+)/','<a href=/hash/$1>$0</a>',$string);
echo $text; // output will be www.funnenjoy.com is best <a href=search/SocialNetworking>#SocialNetworking</a> <a href=/search/website>#website</a>
Extract multiple hashtag to array
$body = 'My #name is #Eminem, I am rap #god, #Yoyoya check it #out';
$hashtag_set = [];
$array = explode('#', $body);
foreach ($array as $key => $row) {
$hashtag = [];
if (!empty($row)) {
$hashtag = explode(' ', $row);
$hashtag_set[] = '#' . $hashtag[0];
}
}
print_r($hashtag_set);
You can use preg_match_all() PHP function
preg_match_all('/(?<!\w)#\w+/', $description, $allMatches);
will give you only hastag array
preg_match_all('/#(\w+)/', $description, $allMatches);
will give you hastag and without hastag array
print_r($allMatches)
You can extract a value in a string with preg_match function
preg_match("/#(\w+)/", $tweet_text, $matches);
$hash = $matches[1];
preg_match will store matching results in an array. You should take a look at the doc to see how to play with it.
Here's a non Regex way to do it:
<?php
$tweet = "Foo bar #hashTag hello world";
$hashPos = strpos($tweet,'#');
$hashTag = '';
while ($tweet[$hashPos] !== ' ') {
$hashTag .= $tweet[$hashPos++];
}
echo $hashTag;
Demo
Note: This will only pickup the first hashtag in the tweet.

How to parse PHP code in a PHP array?

I am using this piece of code on a site of mine.
If there is PHP code in the array and if you echo it, it does not run.
There is piece of code;
function spin($var){
$words = explode("{",$var);
foreach ($words as $word)
{
$words = explode("}",$word);
foreach ($words as $word)
{
$words = explode("|",$word);
$word = $words[array_rand($words, 1)];
echo $word." ";
}
}
}
$text = "example.com is {the best forum|a <? include(\"myfile.php\");?>Forum|a wonderful Forum|a perfect Forum} {123|some other sting}";
spin($text);
The file that needs to be included "myfile.php" will not be included. and the PHP codes will be visible. Why is that? How can I solve this problem?
I believe that you will want to run the include statement through eval(). However note that:
"The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand." (PHP.net)
SOURCE: http://php.net/manual/en/function.eval.php
You might try the following:
<?php
function spin($var)
{
$words = explode("\{",$var);
foreach ($words as $word)
{
$words = explode("}",$word);
foreach ($words as $word)
{
$words = explode("|",$word);
$word = $words[array_rand($words, 1)];
if ( preg_match( "/\<\? include\(\\\"([A-Za-z\.]+)\\\"\)\;\?\>/", $word ) )
{
$file = preg_replace( "/^.*\<\? include\(\\\"([A-Za-z\.]+)\\\"\)\;\?\>.*\$/", "\$1", $word );
$pre = preg_replace( "/^(.*)\<\? include\(\\\"[A-Za-z\.]+\\\"\)\;\?\>.*\$/", "\$1", $word );
$post = preg_replace( "/^.*\<\? include\(\\\"[A-Za-z\.]+\\\"\)\;\?\>(.*)\$/", "\$1", $word );
echo $pre;
include( $file );
echo $post;
}
}
}
}
$text = "example.com is {the best forum|a <? include(\"myfile.php\");?>Forum|a wonderful Forum|a perfect Forum} {123|some other sting}";
spin($text);
?>
My suggestion is a bit of other way,
function spin($var){
$words = explode("{",$var);
foreach ($words as $word)
{
$words = explode("}",$word);
foreach ($words as $word)
{
$words = explode("|",$word);
$word = $words[array_rand($words, 1)];
if(str_replace(" ","",$word) == 'thisparam'){
echo 'a';
include("myfile.php");
echo 'Forum';
}else{
echo $word." ";
}
}
}
}
$text = "example.com is {the best forum| thisparam |a wonderful Forum|a perfect Forum} {123|some other sting}";
spin($text);
where thisparam is you variable $test is the parameter to run the if statement.
I place a str_replace infront of $word to replace strings to get exact word.
Well it is just a string of text after all. The echo will just output the text...
I suggest you look to make use of eval http://php.net/manual/en/function.eval.php
I cant really tell why you wish to do this though. Whenever I need to use eval and friends I stop to think "Should I be doing this?"

Categories