PHP - Exploding each item in an array created by explode - php

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];

Related

PHP search for string in text file & return result after specific character

i want search string in text file. find result and return after : character.
input is alex
text file include this item
alex:+123
david:+1345
john:+1456
output is +123
$input = "alex";
file_get_contents("TextFilePath");
//in this step i don't know what should i do
Maybe not the best solution, but you can use file and loop on the array. explode each line to see if the needle was present.
function findInAFile($filename, $needle) {
// read file split on newline
$lines = file($filename);
// check each line and return first occurence
foreach ($lines as $line) {
$arr = explode($needle, $line, 2);
if (isset($arr[1])) {
return $arr[1];
}
}
}
echo findInAFile('file.txt', $input.':');
You can use a regular expression match to locate lines beginning with the given input:
$input = "alex";
$text = file_get_contents("TextFilePath");
if (preg_match('#^' . preg_quote($input) . ':(.*)#m', $text, $match) {
// Found input
var_dump($match[1]);
}

Backreference preg_replace with commas in subject

Can you please help me find the preg_replace syntax so i can duplicate the price where it is missing?
The subject is:
...nomaterwhat13124123,"321,00",,nomaterwhat
...nomaterwhat12321,"322,20","134,00",nomaterwhat
...nomaterwhat1321,"211,00",,nomaterwhat
...nomaterwhat31313,"241,00",,nomaterwhat
My output want to be:
...nomaterwhat13124123,"321,00","321,00",nomaterwhat
...nomaterwhat12321,"322,20","134,00",nomaterwhat
...nomaterwhat1321,"211,00","211,00",nomaterwhat
...nomaterwhat31313,"241,00","241,00",nomaterwhat
I tried
preg_replace("(\W+),,nomaterwhat$", "$1,$1,nomaterwhat", $string);
Ignoring more complex cases this should do:
$result = preg_replace('/,"(\d+,\d{2})",,nomaterwhat/', ',"$1",$1,nomaterwhat', $string);
If you use str_getcsv you can do something like this:
$data = "CSV VALUES";
$lines = explode("\n", $data);
foreach ($lines as $line) {
$temp = str_getcsv($line);
echo '<pre>' . print_r($temp, true) . '</pre>';
}
Then you can put these into an array like so:
$data = "CSV VALUES";
$lines = explode("\n", $data);
$output = array();
foreach ($lines as $line) {
$temp = str_getcsv($line);
$temp[5] = ($temp[5] == '') ? $temp[4] : $temp[5];
$output[] = $temp;
}
echo '<pre>' . print_r($output, true) . '</pre>';
Replace $temp[5] with the place that the 2nd price should be.
You have a few issues with your regex.
1. No delimiter
2. No m modifier so $ is the end of the string, not line.
3. \W+ is a non a-z, 0-9, and/or _ so you wouldn't have gotten the
money value there anyway.
Try this out:
$string = '...nomaterwhat13124123,"321,00",,nomaterwhat
...nomaterwhat12321,"322,20","134,00",nomaterwhat
...nomaterwhat1321,"211,00",,nomaterwhat
...nomaterwhat31313,"241,00",,nomaterwhat';
echo preg_replace("/,(\"\d+,\d{2}\"),,nomaterwhat$/m", ",$1,$1,nomaterwhat", $string);
Output:
...nomaterwhat13124123,"321,00","321,00",nomaterwhat
...nomaterwhat12321,"322,20","134,00",nomaterwhat
...nomaterwhat1321,"211,00","211,00",nomaterwhat
...nomaterwhat31313,"241,00","241,00",nomaterwhat
Regex Demo: https://regex101.com/r/hE2zQ7/1
PHP Demo: http://ideone.com/OanPN1

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

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;
}

Get value from file - php

Let's say I have this in my text file:
Author:MJMZ
Author URL:http://abc.co
Version: 1.0
How can I get the string "MJMZ" if I look for the string "Author"?
I already tried the solution from another question (Php get value from text file) but with no success.
The problem may be because of the strpos function. In my case, the word "Author" got two. So the strpos function can't solve my problem.
Split each line at the : using explode, then check if the prefix matches what you're searching for:
$lines = file($filename, FILE_IGNORE_NEW_LINES);
foreach($lines as $line) {
list($prefix, $data) = explode(':', $line);
if (trim($prefix) == "Author") {
echo $data;
break;
}
}
Try the following:
$file_contents = file_get_contents('myfilename.ext');
preg_match('/^Author\s*\:\s*([^\r\n]+)/', $file_contents, $matches);
$code = isset($matches[1]) && !empty($matches[1]) ? $matches[1] : 'no-code-found';
echo $code;
Now the $matches variable should contains the MJMZ.
The above, will search for the first instance of the Author:CODE_HERE in your file, and will place the CODE_HERE in the $matches variable.
More specific, the regex. will search for a string that starts with the word Author followed with an optional space \s*, followed by a semicolon character \:, followed by an optional space \s*, followed by one or more characters that it is not a new line [^\r\n]+.
If your file will have dinamically added items, then you can sort it into array.
$content = file_get_contents("myfile.txt");
$line = explode("\n", $content);
$item = new Array();
foreach($line as $l){
$var = explode(":", $l);
$value = "";
for($i=1; $i<sizeof($var); $i++){
$value .= $var[$i];
}
$item[$var[0]] = $value;
}
// Now you can access every single item with his name:
print $item["Author"];
The for loop inside the foreach loop is needed, so you can have multiple ":" in your list. The program will separate name from value at the first ":"
First take lines from file, convert to array then call them by their keys.
$handle = fopen("file.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$pieces = explode(":", $line);
$array[$pieces[0]] = $pieces[1];
}
} else {
// error opening the file.
}
fclose($handle);
echo $array['Author'];

PHP: Normalize a string

I want to normalize (so canonicalize) a string into the normal form for names:
First letter of the name is uppercase
The difficulty by this is now to follow this rule with second and third name.
My method:
public function namilize($string)
{
$strings = explode(' ', $string);
foreach ($strings as $string) {
$string = ucfirst(strtolower($string));
}
$string = implode(' ', $strings);
return $string;
}
Somehow the
$string = ucfirst(strtolower($string));
fails.
What do I have to correct?
Is there a better way?
Regards
EDIT:
Hi,
thank you all for all the comments and answers.
I found another "modern" method:
public function namilize($string)
{
$string = mb_convert_case($string, MB_CASE_TITLE, mb_detect_encoding($string));
}
When I now would additionally add some regex for Mc and O's than it would be complete :)
public function namilize($name) {
$name = strtolower($name);
$normalized = array();
foreach (preg_split('/([^a-z])/', $name, NULL, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) as $word) {
if (preg_match('/^(mc)(.*)$/', $word, $matches)) {
$word = $matches[1] . ucfirst($matches[2]);
}
$normalized[] = ucfirst($word);
}
return implode('', $normalized);
}
Note that this will work for names like John O'Brian, James McManus, etc. For other names with prefixes like McManus, simply add the prefix to the preg_match(). Obviously, this runs the possibility of false positives, but no method is going to be 100% foolproof.
You have to pass the $string by reference, note the &:
public function namilize($string)
{
$strings = explode(' ', $string);
foreach ($strings as &$string) {
$string = ucfirst(strtolower($string));
}
$string = implode(' ', $strings);
return $string;
}
Or use the function suggested by #thetaiko ucwords($string)
The $string inside the foreach will only store the last iteration (or the last name). This doesn't really matter though because the variable in the foreach is never used for output. The implode just undoes what you did with the explode so you will end up with the exact same output as the input. I changed the variable names to be more descriptive in this example:
function namilize($name_in)
{
$a_names = explode(' ', $name_in); //explode string into array
foreach ($a_names as $name) {
$a_fullname[] = ucfirst(strtolower($name)); //build array of proper case names
}
$string = implode(' ', $a_fullname); //convert array into string
return $string;
}

Categories