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.
Related
Suppose I have a string (which contain array of objects):
$string = "[{'test':'1', 'anothertest':'2'}, {'test':'3', 'anothertest':'4'}]";
My goals is to get the output to look like this when I print_r:
Array
(
[0] => Array
(
[test] => 1
[anothertest] => 2
)
[1] => Array
(
[test] => 3
[anothertest] => 4
)
)
I tried to json_decode($string) but it returned NULL
Also tried my own workaround which is kinda solved the problem,
$string = "[{'test':'1', 'anothertest':'2'}, {'test':'3', 'anothertest':'4'}]";
$string = substr($string, 1, -1);
$string = str_replace("'","\"", $string);
$string = str_replace("},","}VerySpecialSeparator", $string);
$arrayOfString = explode("VerySpecialSeparator",$string);
$results = [];
foreach($arrayOfString as $string) {
$results[] = json_decode($string, true);
}
echo "<pre>";
print_r($results);
die;
But is there any other ways to solve this?
As per your given data, if quotes will be corrected, then you will get your desired output, so get it done like below:
<?php
$string = "[{'test':'1', 'anothertest':'2'}, {'test':'3', 'anothertest':'4'}]";
$string = str_replace("'",'"', $string);
print_r(json_decode($string,true));
https://3v4l.org/PDI7O
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.
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;
}
I have a string with custom markup for saving songs with chords, tabulatures, notes etc. It contains
things in various brackets: \[.+?\], \[[.+?\]], \(.+?\)
arrows: <-{3,}>, \-{3,}>, <\-{3,}
and so on...
Sample text might be
Text Text [something]
--->
Text (something 021213)
Now I wish to parse the markup into array of tokens, objects of corresponding classes, which would look like (matched parts in brackets)
ParsedBlock_Text ("Text Text ")
ParsedBlock_Chord ("something")
ParsedBlock_Text (" ")
ParsedBlock_NewColumn
ParsedBlock_Text (" text ")
ParsedBlock_ChordDiagram ("something 021213")
I know how to match them, but either I must match each different pattern, and save offsets to properly sort the array, or I match them at once and I don't know which one has been matched.
Thanks, MK
Assuming you do not try to nest these structures, this will tokenize your text:
function ParseText($text) {
$re = '/\[\[(?P<DoubleBracket>.*?)]]|\[(?P<Bracket>.*?)]|\((?P<Paren>.*?)\)|(?<Arrow><---+>?|---+>)/s';
$keys = array('DoubleBracket', 'Bracket', 'Paren', 'Arrow');
$result = array();
$lastStart = 0;
if (preg_match_all($re, $text, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE)) {
foreach ($matches as $match) {
$start = $match[0][1];
$prefix = substr($text, $lastStart, $start - $lastStart);
$lastStart = $start + strlen($match[0][0]);
if ($prefix != '' && !ctype_space($prefix)) {
$result []= array('Text', trim($prefix));
}
foreach ($keys as $key) {
if (isset($match[$key]) && $match[$key][1] >= 0) {
$result []= array($key, $match[$key][0]);
break;
}
}
}
}
$prefix = substr($text, $lastStart);
if ($prefix != '' && !ctype_space($prefix)) {
$result []= array('Text', trim($prefix));
}
return $result;
}
Example:
$mytext = <<<'EOT'
Text Text [something]
--->
Text (something 021213)
More Text
EOT;
$parsed = ParseText($mytext);
foreach ($parsed as $item) {
print_r($item);
}
Output:
Array
(
[0] => Text
[1] => Text Text
)
Array
(
[0] => Bracket
[1] => something
)
Array
(
[0] => Arrow
[1] => --->
)
Array
(
[0] => Text
[1] => Text
)
Array
(
[0] => Paren
[1] => something 021213
)
Array
(
[0] => Text
[1] => More Text
)
http://ideone.com/kJQrBw
If you want to add more patterns to the regex, make sure you put longer patterns at the start, so they are not mistakenly matched as the wrong type.
I want to parse a file, and store it into an Array in PHP. However, there are some rules which should the observed:
(p="value") should be ignored, but the "value" should be preserved.
- should be ignored.
whitespaces should be ignored.
split by \t and \n.
A sample string is :
NPD4196-2a_5_0
Geldanamycin - 0.166516 (p = 0.0068) Alamethicin - 0.158302 (p = 0.0206) 4-Hydroxytamoxifen - 0.1429 (p = 0.0183) Abietic acid - 0.133045 (p = 0.0203) Caspofungin - 0.130885 (p = 0.0432) Extract 00-303C - 0.12858 (p = 0.0356) U73122 - 0.113274 (p = 0.0482) Radicicol - 0.10213 (p = 0.0356) Calcium ionophore - 0.096183 (p = 0.0262)
So, the goal is to produce a data structure like:
Array('NPD4196-2a_5_0' => Array(Array( 0 => 'Geldanamycin', 1 => '0.166516', 2 => '0.0068'), Array( ... ));
I have this written so far ...
while(($line = fgets($fp)) !== false){
$args = preg_split( '/[\t\n (=) ]+/', $line, -1, PREG_SPLIT_NO_EMPTY );
if(count($args)){
print_r($args);
print "\n";
}
}
What am I missing in other to accomplish my goal?
Thanks
(.+?)-\s*([\d\.]+)\s*\(p\s*=\s*([\d\.]+)\)
That will grab the element (e.g. Geldanamycin) in group 1, the related value in group 2, and the p value in group 3.
Play with the regex here.
This seems to work for one key-value pair (assuming NPD4196-2a_5_0 is the key in your example, and the second line is the value).
<?php
$fp = fopen('foo.txt', 'r');
$regex = '/(\w*)\s*-\s*([\d\.]+)\s*\(p\s*=\s*([\d\.]+)\)/';
$id = "NO ID";
$result = Array();
while(($line = fgets($fp)) !== false){
if (!preg_match($regex, $line)) {
$id = chop($line);
} else {
$all = Array();
while (preg_match($regex, $line, $matches, PREG_OFFSET_CAPTURE)) {
$last = end($matches);
$line = substr($line, $last[1] + strlen($last[0]) + 1);
$strings = Array();
for ($i = 1; $i < 4; $i++) {
array_push($strings, $matches[$i][0]);
}
array_push($all, $strings);
}
$result[$id] = $all;
}
}
print_r($result);
?>
(That is a slightly edited version of David B's regex.)
If the line doesn't match that long RegEx pattern, it will store the line as the ID. Otherwise, it will match the RegEx, then chop off the matching part. Each iteration of the inner while loop will match one entry. Since I am grabbing the indices of the matches, the for loop is used to only add the strings to the result.
This prints:
Array
(
[NPD4196-2a_5_0] => Array
(
[0] => Array
(
[0] => Geldanamycin
[1] => 0.166516
[2] => 0.0068
)
[1] => Array
(
[0] => Alamethicin
[1] => 0.158302
[2] => 0.0206
)
[2] => Array
(
[0] => Hydroxytamoxifen
[1] => 0.1429
[2] => 0.0183
)
...