Multi-array with one output - php

Here is my code, which currently does not working properly. How can I make it working? My wish is to make output like one string (of course I know how to "convert" array to string):
words altered, added, and removed to make it
Code:
<?php
header('Content-Type: text/html; charset=utf-8');
$text = explode(" ", strip_tags("words altered added and removed to make it"));
$stack = array();
$words = array("altered", "added", "something");
foreach($words as $keywords){
$check = array_search($keywords, $text);
if($check>(-1)){
$replace = " ".$text[$check].",";
$result = str_replace($text[$check], $replace, $text);
array_push($stack, $result);
}
}
print_r($stack);
?>
Output:
Array
(
[0] => Array
(
[0] => words
[1] => altered,
[2] => added
[3] => and
[4] => removed
[5] => to
[6] => make
[7] => it
)
[1] => Array
(
[0] => words
[1] => altered
[2] => added,
[3] => and
[4] => removed
[5] => to
[6] => make
[7] => it
)
)

Without more explanation it's as simple as this:
$text = strip_tags("words altered added and removed to make it");
$words = array("altered", "added", "something");
$result = $text;
foreach($words as $word) {
$result = str_replace($word, "$word,", $result);
}
Don't explode your source string
Loop the words and replace the word with the word and added comma
Or abandoning the loop approach:
$text = strip_tags("words altered added and removed to make it");
$words = array("altered", "added", "something");
$result = preg_replace('/('.implode('|', $words).')/', '$1,', $text);
Create a pattern by imploding the words on the alternation (OR) operator |
Replace found word with the word $1 and a comma

You can use an iterator
// Array with your stuff.
$array = [];
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($iterator as $value) {
echo $v, " ";
}

Your original approach should work with a few modifications. Loop over the words in the exploded string instead. For each one, if it is in the array of words to modify, add the comma. If not, don't. Then the modified (or not) word goes on the stack.
$text = explode(" ", strip_tags("words altered added and removed to make it"));
$words = array("altered", "added", "something");
foreach ($text as $word) {
$stack[] = in_array($word, $words) ? "$word," : $word;
}

Related

How do I put a specific string from an array that came from a file in PHP?

Hi I have been doing this project for almost a month now. Is there's anyway I can store the value of the next string after the searched string in the list of array?
For example:
Deviceid.txt content is:
Created:21/07/2016 1:50:53; Lat:30.037853; Lng:31.113798; Altitude:79; Speed:0; Course:338; Type:Gps;
Created:21/07/2016 1:49:53; Lat:30.037863; Lng:31.113733; Altitude:60; Speed:0; Course:338; Type:Gps;
Here is my sample php coding
$file_handle = fopen("data/deviceid.txt", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
array_push($a,$line);
}
$searchword = 'Lat';
$matches = array_filter($a, function($var) use ($searchword) {
return preg_match("/\b$searchword\b/i", $var);
});
print_r($matches);
fclose($file_handle);
Matches Data:
[0] = 30.037853
[1] = 30.037863
After parsing the file with the code below, you can use array_column (php v5.5.0+) to get all values from a specific key, like so:
array_column($parsed, 'Lat');
Output:
Array
(
[0] => 30.037853
[1] => 30.037863
)
See it in action here.
And here is the code to parse the content of the file:
// $a = each line of the file, just like you're doing
$a = array_filter($a); // remove empty lines
$parsed = array();
foreach($a as $v1){
$a1 = explode(';', $v1);
$tmp = array();
foreach($a1 as $v2){
$t2 = explode(':', $v2);
if(count($t2) > 1){
$tmp[trim(array_shift($t2))] = trim( implode(':', $t2) );
}
}
$parsed[] = $tmp;
}
This is the structure of $parsed:
Array
(
[0] => Array
(
[Created] => 21/07/2016 1:50:53
[Lat] => 30.037853
[Lng] => 31.113798
[Altitude] => 79
[Speed] => 0
[Course] => 338
[Type] => Gps
)
[1] => Array
(
[Created] => 21/07/2016 1:49:53
[Lat] => 30.037863
[Lng] => 31.113733
[Altitude] => 60
[Speed] => 0
[Course] => 338
[Type] => Gps
)
)
See the code in action here.
I wrote a quick regex that can help you pull the field names and values from each line.
You may try with this:
$re = "/((?P<fieldname>[^\\:]*)\\:(?P<fieldvalue>[^\\;]*); *)/";
$str = "Created:21/07/2016 1:50:53; Lat:30.037853; Lng:31.113798; Altitude:79; Speed:0; Course:338; Type:Gps;";
preg_match_all($re, $str, $matches);
Do a print_r of $matches to inspect the results.
Hope this helps.
After your array_filter, iterate through your matches and apply a more specific regex to each line:
$lats = array();
foreach ($matches as $line)
{
$match = array();
preg_match("/\b$searchword:([\d\.]+);/i", $var, $match);
$lats[] = $match[1];
}
print_r($lats);
The variable $match will be populated with the full regex match at index 0, and the parenthesized match at index 1.

PHP Array Inconsistency?

I have some code that pushes values into a PHP array via array_push(). However, when I do print_r() on the array, it skips a key, and the ending result looks like this:
Array (
[0] => appease
[1] => cunning
[2] => derisive
[3] => effeminate
[4] => grievance
[5] => inadvertently miscreants
[7] => ominous
[8] => resilient
[9] => resolute
[10] => restrain
[11] => superfluous
[12] => trudged
[13] => undiminished
)
As you can see, it skipped the 6th value, and moved onto the next one. For some reason though, if I call the foreach() method on the array, it stops after "grievance", or index 4. Does anyone know why it does this?
Edit: if I do echo $words[6], it prints the value of the 6th index correctly.
Edit 2: here's my code:
$return = file_get_contents($target_file);
$arr = explode('<U><B>', $return);
$a = 1;
$words = [];
foreach($arr as $pos) {
$important = substr($arr[$a], 0, 20);
$arr2 = explode("</B></U>",$important);
array_push($words,strtolower(trim($arr2[0])));
$a++;
}
Contents of the file are:
<U><B>appease</B></U><U><B>cunning</B></U><U><B>derisive</B></U><U><B>effeminate</B></U><U><B>grievance</B></U><U><B>inadvertently</B></U><U><B>miscreants</B></U><U><B>ominous</B></U><U><B>resilient</B></U><U><B>resolute</B></U><U><B>restrain</B></U><U><B>superfluous</B></U><U><B>trudged</B></U><U><B>undiminished</B></U>
*removed some irrelevant file content for easier readability
i wrote something simplier:
<?php
$return="<U><B>appease</B></U><U><B>cunning</B></U><U><B>derisive</B></U><U><B>effeminate</B></U><U><B>grievance</B></U><U><B>inadvertently</B></U><U><B>miscreants</B></U><U><B>ominous</B></U><U><B>resilient</B></U><U><B>resolute</B></U><U><B>restrain</B></U><U><B>superfluous</B></U><U><B>trudged</B></U><U><B>undiminished</B></U>";
$arr = explode('<U><B>', $return);
$words = [];
foreach($arr as $pos) {
if(!empty($pos)){
$words[]=strip_tags($pos);
}
}
echo '<pre>';
print_r($words);
demo: http://codepad.viper-7.com/XeUWui
$arr = "<U><B>appease</B></U><U><B>cunning</B></U><U><B>derisive</B></U><U><B>effeminate</B></U><U><B>grievance</B></U><U><B>inadvertently</B></U><U><B>miscreants</B></U><U><B>ominous</B></U><U><B>resilient</B></U><U><B>resolute</B></U><U><B>restrain</B></U><U><B>superfluous</B></U><U><B>trudged</B></U><U><B>undiminished</B></U>";
$arr = explode('<U><B>', $arr);
$a = 1;
foreach($arr as &$pos)
{
if(!empty($pos))
{
$pos = str_replace("</B></U>","",$pos);
}
}
print_r(array_filter($arr));
Might be overkill but there is always SimpleXml as well:
$arr = "<U><B>appease</B></U><U><B>cunning</B></U><U><B>derisive</B></U><U><B>effeminate</B></U><U><B>grievance</B></U><U><B>inadvertently</B></U><U><B>miscreants</B></U><U><B>ominous</B></U><U><B>resilient</B></U><U><B>resolute</B></U><U><B>restrain</B></U><U><B>superfluous</B></U><U><B>trudged</B></U><U><B>undiminished</B></U>";
$xml = new SimpleXmlElement('<root>' . $arr . '</root>');
$words = $xml->xpath('//B');
foreach ($words as $i =>$word) {
printf("%d.\t%s\n", $i+1, $word);
}
This is pretty simple with regex:
<?php
$words = "<U><B>appease</B></U><U><B>cunning</B></U><U><B>derisive</B></U><U><B>effeminate</B></U><U><B>grievance</B></U><U><B>inadvertently</B></U><U><B>miscreants</B></U><U><B>ominous</B></U><U><B>resilient</B></U><U><B>resolute</B></U><U><B>restrain</B></U><U><B>superfluous</B></U><U><B>trudged</B></U><U><B>undiminished</B></U>";
preg_match_all("#<U><B>(.*?)</B></U>#",$words,$matches);
print_r($matches[1]);
?>
Fiddle here

PHP - Searching for string and outputting into new string

Let's say I put the following into a textbox:
1|[Guangzhou Evergrande](//www.gzevergrandefc.com/)|6|5-1-0|+15|**16**
2|[Shandong Luneng](//www.lunengsports.com/)|7|5-1-1|+7|**16**
3|[Qingdao Jonoon](//www.zhongnengfc.com/)|7|4-3-0|+4|**15**
4|[Beijing Guoan](//www.fcguoan.com/)|7|3-3-1|+2|**12**
when I press enter, it would take what's between the [ and ] and ( and ) and put it into new lines like this:
if ($name == "NAME_HERE") $name = "[".$name."](URL_HERE)";
I tried doing preg_match and using this pattern: $pattern = '/^[/'; and $pattern_end = '/^]/'; for the name -- jsut to test -- but I cannot get it to work....
Here is what I have so far:
$string = '1|[Guangzhou Evergrande](//www.gzevergrandefc.com/)|6|5-1-0|+15|**16**';
$pattern = '/\[(.*?\)].*?\((.*?)\)/';
$replacement = 'if ($name == "{1}") $name = "[".$name."]({2})";';
echo preg_replace($pattern, $replacement, $string);
Your pattern should be
'/\[(.*?)\]\((.*?)\)/'
because [ ] and ( ) are special characters. Use preg_match_all() function
when you use preg_match_all you can put () for submatches(subpattern)
example
<?php
$string = '1|[Guangzhou Evergrande](//www.gzevergrandefc.com/)|6|5-1-0|+15|**16**';
$matches = array();
preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $string, $matches);
var_dump($matches);
?>
Perhaps I don't fully understand what you are doing here, but, I see a data structure that can be exploded without a hassle. For example:
function get_football( $text ) {
$r = array();
$t = explode("\n", $text );
foreach( $t as $l ) {
$n = explode("|", $l);
$r[] = $n;
}
return( $r );
}
This will get you a nicely structured set of data that you can foreach() through and further process. If the original text is stored inside $variable0, print_r( get_football( $variable0 ) ); will show a nice structure:
Array
(
[0] => Array
(
[0] => 1
[1] => [Guangzhou Evergrande](//www.gzevergrandefc.com/)
[2] => 6
[3] => 5-1-0
[4] => +15
[5] => **16**
)
[1] => Array
Of course, that $n[1] name can be broken down further in the loop. Anyhow, thereafter, you can loop through whatever menu you're building with a foreach() loop instead of hardcoding menu choices. Just something to consider.

string to array, split by single and double quotes

i'm trying to use php to split a string into array components using either " or ' as the delimiter. i just want to split by the outermost string. here are four examples and the desired result for each:
$pattern = "?????";
$str = "the cat 'sat on' the mat";
$res = preg_split($pattern, $str);
print_r($res);
/*output:
Array
(
[0] => the cat
[1] => 'sat on'
[2] => the mat
)*/
$str = "the cat \"sat on\" the mat";
$res = preg_split($pattern, $str);
print_r($res);
/*output:
Array
(
[0] => the cat
[1] => "sat on"
[2] => the mat
)*/
$str = "the \"cat 'sat' on\" the mat";
$res = preg_split($pattern, $str);
print_r($res);
/*output:
Array
(
[0] => the
[1] => "cat 'sat' on"
[2] => the mat
)*/
$str = "the 'cat \"sat\" on' the mat 'when \"it\" was' seventeen";
$res = preg_split($pattern, $str);
print_r($res);
/*output:
Array
(
[0] => the
[1] => 'cat "sat" on'
[2] => the mat
[3] => 'when "it" was'
[4] => seventeen
)*/
as you can see i only want to split by the outermost quotation, and i want to ignore any quotations within quotations.
the closest i have come up with for $pattern is
$pattern = "/((?P<quot>['\"])[^(?P=quot)]*?(?P=quot))/";
but obviously this is not working.
You can use preg_split with the PREG_SPLIT_DELIM_CAPTURE option. The regular expressions is not quite as elegant as #Jan TuroĊˆ's back reference approach because the required capture group messes up the results.
$str = "the 'cat \"sat\" on' the mat the \"cat 'sat' on\" the mat";
$match = preg_split("/('[^']*'|\"[^\"]*\")/U", $str, null, PREG_SPLIT_DELIM_CAPTURE);
print_r($match);
You can use just preg_match for this:
$str = "the \"cat 'sat' on\" the mat";
$pattern = '/^([^\'"]*)(([\'"]).*\3)(.*)$/';
if (preg_match($pattern, $str, $matches)) {
printf("[initial] => %s\n[quoted] => %s\n[end] => %s\n",
$matches[1],
$matches[2],
$matches[4]
);
}
This prints:
[initial] => the
[quoted] => "cat 'sat' on"
[end] => the mat
Here is an explanation of the regex:
/^([^\'"]*) => put the initial bit until the first quote (either single or double) in the first captured group
(([\'"]).*\3) => capture in \2 the text corresponding from the initial quote (either single or double) (that is captured in \3) until the closing quote (that must be the same type as the opening quote, hence the \3). The fact that the regexp is greedy by nature helps to get from the first quote to the last one, regardless of how many quotes are inside.
(.*)$/ => Capture until the end in \4
Yet another solution using preg_replace_callback
$result1 = array();
function parser($p) {
global $result1;
$result1[] = $p[0];
return "|"; // temporary delimiter
}
$str = "the 'cat \"sat\" on' the mat 'when \"it\" was' seventeen";
$str = preg_replace_callback("/(['\"]).*\\1/U", "parser", $str);
$result2 = explode("|",$str); // using temporary delimiter
Now you can zip those arrays using array_map
$result = array();
function zipper($a,$b) {
global $result;
if($a) $result[] = $a;
if($b) $result[] = $b;
}
array_map("zipper",$result2,$result1);
print_r($result);
And the result is
[0] => the
[1] => 'cat "sat" on'
[2] => the mat
[3] => 'when "it" was'
[4] => seventeen
Note: I'd would be probably better to create a class doing this feat, so the global variables can be avoided.
You can use back references and ungreedy modifier in preg_match_all
$str = "the 'cat \"sat\" on' the mat 'when \"it\" was' seventeen";
preg_match_all("/(['\"])(.*)\\1/U", $str, $match);
print_r($match[0]);
Now you have your outermost quotation parts
[0] => 'cat "sat" on'
[1] => 'when "it" was'
And you can find the rest of the string with substr and strpos (kind of blackbox solution)
$a = $b = 0; $result = array();
foreach($match[0] as $part) {
$b = strpos($str,$part);
$result[] = substr($str,$a,$b-$a);
$result[] = $part;
$a = $b+strlen($part);
}
$result[] = substr($str,$a);
print_r($result);
Here is the result
[0] => the
[1] => 'cat "sat" on'
[2] => the mat
[3] => 'when "it" was'
[4] => seventeen
Just strip eventual empty heading/trailing element if the quotation is at the very beginning/end of the string.

Big string to nice array

I need to make big string into a nice array. String itself is list of tags and tag ids. There can be any amount of them. Here is example of the string: 29:funny,30:humor,2:lol - id:tag_name. Now, I have problem converting it to array - Array ( [29] => funny [30] => humor ). I can get to the part where tags are as so
Array (
[0] = Array (
[0] = 29
[1] = funny
)
[1] = Array (
[0] = 30
[1] = humor
)
)
I've look at array functions too but seems none of them could help me.
Can anyone help me out?
Here's some code to get you going:
$str = "29:funny,30:humor,2:lol";
$arr = array();
foreach (explode(',', $str) as $v) {
list($key, $val) = explode(':', $v);
$arr[$key] = $val;
}
print_r($arr);
/* will output:
Array
(
[29] => funny
[30] => humor
[2] => lol
)
*/
You could replace the foreach with an array_map for example, but I think it's simpler for you this way.
Here's an example of it working: http://codepad.org/4BpnCiEJ
You could use explode() to do this, though it would take two passes. The first to split the string into pairings (explode (',', $string)) and the second to split each paring
$arr = explode (',', $string);
foreach ($arr as &$pairing)
{
$pairing = explode (':', $pairing);
}
$string = '29:funny,30:humor,2:lol';
$arr1 = explode(',', $string);
$result = array();
foreach ($arr1 as $element1) {
$result[] = explode(':', $element1);
}
print_r($result);
You can use preg_match_all
preg_match_all('#([\d]+):([a-zA-Z0-9]+)#', $sString, $aMatches);
// Combine the keys with the values.
$aArray = array_combine($aMatches[1], $aMatches[2]);
echo "<pre>";
print_r($aArray);
echo "</pre>";
Outputs:
Array
(
[29] => funny
[30] => humor
[2] => lol
)
<?php
$test = '29:funny,30:humor,2:lol';
$tmp_array = explode(',', $test);
$tag_array = ARRAY();
foreach ($tmp_array AS $value) {
$pair = explode(':', $value);
$tag_array[$pair[0]] = $pair[1];
}
var_dump($tag_array);
?>

Categories