Prepend each line of a variable with a string - php

How can I prepend a string, say 'a' stored in the variable $x to each line of a multi-line string variable using PHP?

Can also use:
echo preg_replace('/^/m', $prefix, $string);
The / are delimiters. The ^ matches the beginning of a string. the m makes it multiline.
demo

There are many ways to achieve this.
One would be:
$multi_line_var = $x.str_replace("\n", "\n".$x, $multi_line_var);
Another would be:
$multi_line_var = explode("\n", $multi_line_var);
foreach($multi_line_var AS &$single_line_var) {
$single_line_var = $x.$single_line_var;
}
$multi_line_var = implode("\n", $multi_line_var);
Or as a deceitfully simple onliner:
$multi_line_var = $x.implode("\n".$x, explode("\n", $multi_line_var));
The second one is dreadfully wasteful compared to the first. It allocates memory for an array of strings. It runs over each array item and modifies it. And the glues the pieces back together.
But it can be useful if one concatenation is not the only alteration you're doing to those lines of text.

Because of your each line requirement, I would first split the string to an array using explode, then loop through the array and add text to the beginning of each line, and then turn the array back to a string using implode. As long as the number of lines is not very big, this can be a suitable solution.
Code sample:
$arr = explode("\n", $x);
foreach ($arr as $key => $value) {
$arr[$key] = 'a' . $arr[$key];
}
$x = implode("\n", $arr);
Example at: http://codepad.org/0WpJ41LE

Related

Add commas in between <a>-elements in a string with php

Is it possible with php to make a string of, say, <a>-elements comma-separated?
The situation is that a foreach loop appends a number of <a> links to an $output variable one after the other:
$output = '<a>link</a><a>link</a><a>link</a><a>link</a><a>link</a>';
Is it afterwards possible in php to comma-separate them and achieve the below string?
$output = '<a>link</a>,<a>link</a>,<a>link</a>,<a>link</a>,<a>link</a>';
Or is the most efficient way to add the comma inside the foreach loop (and then to use an if-command to skip the last one, or something like that, since that will add one comma too many)?
$output = preg_replace("/a><a","/a>,<a",$output);
I'd argue that the array implode method is probably most common way to concatenate multiple elements like this, which has already been posted in another answer.
Depending on your situation, this might however not always be the case, so for the sake of completion I'd like to add that you can also use the rtrim function to easily remove any trailing commas when concatenating strings:
foreach($links as $link) {
$output .= '<a>link</a>,';
}
$output = rtrim($output, ',');
Documentation for rtrim can be read here
A simple replace might do the job for you:
preg_replace('/a><a/','a>,<a',$s);
In your foreach loop, rather than concatenating the item on to the end of an existing string, push them to an array:
$parts = array();
foreach($list as $item){
$parts[] = "<a>$item</a>";
}
Then, you can simply join (implode) the array elements together to get your desired result:
$output = implode(',', $parts);
there are 2 solutions
solution 1 (with str_replace()):
$output = '<a>link</a><a>link</a><a>link</a><a>link</a><a>link</a>';
echo str_replace("</a>","</a>,", $output);
Solution 2 (with explode and implode method):
$exploded = explode("</a>",$output);
echo implode("</a>,", $exploded);
Side Note: you can remove the last `"," by using rtrim() method
You can replace </a> with </a>,, then trim the last `,', check Demo
echo rtrim(str_replace("</a>","</a>,",$output),",");

How to get a range of arrays

I have a code which I have to explode my text using "*" as a delimiter.
I have a pattern that always the array [0] and [1] will be excluded and the rest of them need to be included inside a variable, but my problem is that I don't know how to catch dynamically the rest of the arrays that I have to put them all together inside of it.
Specially because my text may have more "*" and explode into more parts, but I have to get them all together. Excluding the [0] and [1]
$item= explode("*",$c7);
print_r($item);
//so now that I know which are my [0] and [1] arrays I need to get the rest of them inside of another variable
$variable = ?? //the rest of the $item arrays
$str = 'a*b*c*d*e';
$newStr = implode('*', array_slice(explode('*', $str), 2)); // OUTPUT: c*d*e
explode() is used to chunk the string by a delimiter
implode() is used to build a string again from chunks
array_slice() is used to select a range of the elements
I realise an answer was already accepted, but explode has a third argument for this, and with end you can grab that last, non-split part:
$str = 'a*b*c*d*e';
$res = end(explode("*", $str, 3));
$res gets this value as a result:
c*d*e
I think based off of your question, if I interpreted it correctly something like below will be useful.
USING A LOOP
$str = "adssa*asdASD*AS*DA*SD*ASD*AS*DAS*D";
$parts = explode("*", $str);
$newStr = "";
for ($i = 2; $i < count($parts); ++$i) {
$newStr .= $parts[$i];
}

Check if URL contains string then create variables with url strings

I need to check if URL contains the term: "cidades".
For example:
http://localhost/site/cidades/sp/sorocaba
So, if positive, then I need to create two or three variables with the remaining content without the " / ", in this case:
$var1 = "sp";
$var2 = "sorocaba";
These variables will be cookies values in the beggining of the page, then, some sections will use as wp-query these values to filter.
This should work for you:
Here I check with preg_match() if the search word is in the url $str between two slashes. If yes I get the substr() from the url after the search word and explode() it into an array with a slash as delimiter. Then you can simply loop through the array an create the variables with complex (curly) syntax.
<?php
$str = "http://localhost/site/cidades/sp/sorocaba";
$search = "cidades";
if(preg_match("~/$search/~", $str, $m, PREG_OFFSET_CAPTURE)) {
$arr = explode("/", substr($str, $m[0][1]+strlen($m[0][0])));
foreach($arr as $k => $v)
${"var" . ($k+1)} = $v;
}
echo $var1 . "<br>";
echo $var2;
?>
output:
sp
sorocaba
Here are two functions that will do it for you:
function afterLast($haystack, $needle) {
return substr($haystack, strrpos($haystack, $needle)+strlen($needle));
}
And PHP's native explode.
First call afterLast, passing the /cidades/ string (or just cidades if you don't expect the slashes). Then take the result and explode on / to get your resulting array.
It would look like:
$remaining_string = afterLast('/cidades/', $url);
$items = explode('/', $remaining_string)
Just note that if you do not include the / marks with the afterLast call, your first element in the explode array will be empty.
I think this solution is better, since the resulting array will support any number of values, not just two.

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.

get the results of curl in variables

i got a piece of code that so far returns me data like this when i use print $result;
ssl_card_number=41**********1111
ssl_exp_date=0213
ssl_amount=132.86
ssl_salestax=0.00
ssl_invoice_number=5351353519500
ssl_result=0
ssl_result_message=APPROVED
ssl_txn_id=00000000-0000-0000-0000-00000000000
ssl_approval_code=123456
ssl_cvv2_response=P
ssl_avs_response=X
ssl_account_balance=0.00
ssl_txn_time=11/21/2012 12:38:20 PM
thats from view page source.
and the page itself shows it as :
ssl_card_number=41**********1111 ssl_exp_date=0213 ssl_amount=132.86 ssl_salestax=0.00 ssl_invoice_number=8601353519473 ssl_result=0 ssl_result_message=APPROVED ssl_txn_id=00000000-0000-0000-0000-00000000000 ssl_approval_code=123456 ssl_cvv2_response=P ssl_avs_response=X ssl_account_balance=0.00 ssl_txn_time=11/21/2012 12:37:54 PM
i need to be able to handle each of the "keys" in a better way and dont know how to explode them maybe ?
One possible approach:
parse_str(preg_replace('#\s+(?=\w+=)#', '&', $result), $array);
var_dump($array);
Explanation: preg_replace will turn all the whitespace before the param names into '&' symbol - making this string similar to the regular GET request url. Then parse_str (the function created specifically for parsing such urls) will, well, parse this string (sent as the first param), making an associative array of it.
In fact, you don't even have to use preg_replace here, if each param=value string begins from a new line; str_replace("\n", '&') should do the trick.
An alternative approach:
$pairs = preg_split('#\s+(?=\w+=)#', $x);
foreach ($pairs as $pair) {
list ($key, $value) = explode('=', $pair, 2);
$array[$key] = $value;
}
Here you first create an array of 'key-value pair' strings, then split each element by =: the first part would be the key, the second - the value.
You can use the regular expression reported by #raina77ow or you could use explodes (riskier):
<?php
$tmps = explode("\n",$result); //this gives you each line separate
foreach($tmps as $tmp){
list($key,$value) = explode('=',$tmp,2);
echo $key.' has value '.$value."\n";
//you can even create vars with the "key" if you are sure that they key is a "clean" string:
$$key=$value;
//or put everything into an array - similar to the regexp
$result_array[$key] = $value;
}
?>

Categories