I am trying to create file links based a variable which has a "prefix" and an extension at the end.
Here's what I have:
$url = "http://www.example.com/mods/" . ereg("^[A-Za-z_\-]+$", $title) . ".php";
Example output of what I wish to have outputted (assuming $title = testing;):
http://www.example.com/mods/testing.php
What it currently outputs:
http://www.example.com/mods/.php
Thanks in advance!
Perhaps this is what you need:
$title = "testing";
if(preg_match("/^[A-Za-z_\-]+$/", $title, $match)){
$url = "http://www.example.com/mods/".$match[0].".php";
}
else{
// Think of something to do here...
}
Now $url is http://www.example.com/mods/testing.php.
Do you want to keep letters and remove all other chars in the URL?
In this case the following should work:
$title = ...
$fixedtitle=preg_replace("/[^A-Za-z_-]/", "", $title);
$url = "http://www.example.com/mods/".$fixedtitle.".php";
the inverted character class will remove everything you do not want.
OK first it's important for you to realize that ereg() is deprecated and will eventually not be available as a command for php, so to prevent an error down the road you should use preg_match instead.
Secondly, both ereg() and preg_match output the status of the match, not the match itself. So
ereg("^[A-Za-z_\-]+$", $title)
will output an integer equal to the length of the string in $title, 0 if there's no match and 1 if there's a match but you didn't pass it another variable to store the matches in.
I'm not sure why it's displaying
http://www.example.com/mods/.php
It should actually be outputting
http://www.example.com/mods/1.php
if everything was working correctly. So there is something going on there, and it's definitely not doing what you want it to. You need to pass another variable to the function that will store all the matches found. If the match is successful (which you can check using the return value of the function) then that variable will be an array of all matches.
Note that with preg_match by default only the first match will be returned. but it will still generate an array (which can be used to get isolated portions of the match) whereas preg_match_all will match multiple things.
See http://www.php.net/manual/en/function.preg-match.php for more details.
Your regex looks more or less correct
So the proper code should look something like:
$title = 'testing'; //making sure that $title is what we think it is
if (preg_match('/^[A-Za-z_\-]+$/',$title,$matches)) {
$url = "http://www.example.com/mods/" . $matches[0] . ".php";
} else {
//match failed, put error code in here
}
Update: Casting as an array does the trick. See this response, since I don't have enough clout to upvote :)
I started on this problem with many potential culprits, but after lots of diagnostics the problem is still there and no obvious answers remain.
I want to print the placename "Gaborone", which is located at the first tag under the first tag under the first tag of this API-loaded XML file. How can I parse this to return that content?
<?php
# load the XML file
$test1 = (string)file_get_contents('http://www.afdb.org/fileadmin/uploads/afdb/Documents/Generic-Documents/IATIBotswanaData.xml');
#throw it into simplexml for parsing
$xmlfile = simplexml_load_string($test1);
#output the parsed text
echo $xmlfile->iati-activity[0]->location[0]->gazetteer-entry;
?>
Which never fails to return this:
Parse error: syntax error, unexpected '[', expecting ',' or ';'
I've tried changing the syntax to avoid the hyphens in the tag names as such:
echo $xmlfile["iati-activity"][0]["location"][0]["gazetteer-entry"];
. . . but that returns complete nothingness; no error, no source.
I've also tried debugging based on these otherwise-helpful threads, but none of the solutions have worked. Is there an obvious error in my simplexml addressing?
I've tried changing the syntax to avoid the hyphens in the tag names
as such: echo
$xmlfile["iati-activity"][0]["location"][0]["gazetteer-entry"];
Your problem here is that, object native casting to an array isn't recursive, so that you did that for primary keys only. And yes, your guess is correct - you shouldn't deal with object properties when working with returned value of simplexml_load_string() because of the syntax issues. Instead, you should cast a returned value of it (stdclass) into an array recursively. You can use this function for that:
function object2array($object) {
return json_decode(json_encode($object), true);
}
The rest:
// load the XML file
$test1 = file_get_contents('http://www.afdb.org/fileadmin/uploads/afdb/Documents/Generic-Documents/IATIBotswanaData.xml');
$xml = simplexml_load_string($test1);
// Cast an object into array, that makes it much easier to work with
$data = object2array($xml);
$data = $data['iati-activity'][0]['location'][0]['gazetteer-entry']; // Works
var_dump($data); // string(8) "Gaborone"
I had a similar problem parsing XML using the simpleXML command until I did the following string replacements:
//$response contains the XML string
$response = str_replace(array("\n", "\r", "\t"), '', $response); //eliminate newlines, carriage returns and tabs
$response = trim(str_replace('"', "'", $response)); // turn double quotes into single quotes
$simpleXml = simplexml_load_string($response);
$json = json_decode(json_encode($simpleXml)); // an extra step I took so I got it into a nice object that is easy to parse and navigate
If that doesn't work, there's some talk over at PHP about CDATA not always being handled properly - PHP version dependent.
You could try this code prior to calling the simplexml_load_string function:
if(strpos($content, '<![CDATA[')) {
function parseCDATA($data) {
return htmlentities($data[1]);
}
$content = preg_replace_callback(
'#<!\[CDATA\[(.*)\]\]>#',
'parseCDATA',
str_replace("\n", " ", $content)
);
}
I've reread this, and I think your error is happening on your final line - try this:
echo $xmlfile->{'iati-activity'}[0]->location[0]->{'gazetteer-entry'};
I am trying to create a report function for our firewall.
The firewall rules are stored in json format.
Here is a sample of the string.
[{"id":1,"enabled":true,"description":"TEMP","matchers":{"javaClass":"java.util.LinkedList","list":[{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1.1.1.1","matcherType":"DST_ADDR"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"80","matcherType":"DST_PORT"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1,3,2","matcherType":"DST_INTF"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"2.2.2.2","matcherType":"SRC_ADDR"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1,2,wan","matcherType":"SRC_INTF"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"UDP,TCP,any","matcherType":"PROTOCOL"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"svrbjgu","matcherType":"DIRECTORY_CONNECTOR_USERNAME"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"intern-it","matcherType":"DIRECTORY_CONNECTOR_GROUP"}]},"ruleId":5001,"javaClass":"com.untangle.node.firewall.FirewallRule","block":false,"log":true}]
And the preg_match_all filter i have:
preg_match_all('/\"description":"(.*?)\","matchers"/',$str,$description);
preg_match_all('/\"id":(.*?)\,"/',$str,$id);
preg_match_all('/\"ruleId":(.*?)\,"/',$str,$rule_id);
preg_match_all('/\"enabled":(.*?)\,"description"/',$str,$enable);
preg_match_all('/\"block":(.*?)\,"/',$str,$block);
preg_match_all('/\"log":(.*?)\}/',$str,$log);
preg_match_all('/\"value":"(.*?)\","matcherType":"DST_ADDR"/',$str,$dest_add);
preg_match_all('/\"value":"(.*?)\","matcherType":"DST_PORT"/',$str,$dest_port);
preg_match_all('/\"value":"(.*?)\","matcherType":"DST_INTF"/',$str,$dest_int);
preg_match_all('/\"value":"(.*?)\,","matcherType":"SRC_ADDR"/',$str,$src_add);
preg_match_all('/\"value":"(.*?)\","matcherType":"SRC_INTF"/',$str,$src_int);
preg_match_all('/\"value":"(.*?)\","matcherType":"PROTOCOL"/',$str,$protocol);
preg_match_all('/\"value":"(.*?)\","matcherType":"DIRECTORY_CONNECTOR_USERNAME"/',$str,$user);
preg_match_all('/\"value":"(.*?)\","matcherType":"DIRECTORY_CONNECTOR_GROUP"/',$str,$group);
What happens is that the start for evry matcher is VALUE":" when i print $dest_port i get "1.1.1.1","matcherType":"DST_ADDR"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"80" instead of just 80.
Any one that have a preg_match_all to find the matchertype first and then read backwords to the "value":"?
Any help would be fantastic!
$xyz = <<<EOX
[{"id":1,"enabled":true,"description":"TEMP","matchers":{"javaClass":"java.util.LinkedList","list":[{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1.1.1.1","matcherType":"DST_ADDR"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"80","matcherType":"DST_PORT"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1,3,2","matcherType":"DST_INTF"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"2.2.2.2","matcherType":"SRC_ADDR"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1,2,wan","matcherType":"SRC_INTF"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"UDP,TCP,any","matcherType":"PROTOCOL"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"svrbjgu","matcherType":"DIRECTORY_CONNECTOR_USERNAME"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"intern-it","matcherType":"DIRECTORY_CONNECTOR_GROUP"}]},"ruleId":5001,"javaClass":"com.untangle.node.firewall.FirewallRule","block":false,"log":true}]
EOX;
var_dump(json_decode($xyz)); //execute other operations, iteration etc here
This works much better than regex. Returns structured data, you can iterate through.
Ended up using with json_decode.
sample:
$jsondata ='[{"id":1,"enabled":true,"description":"TEMP","matchers":{"javaClass":"java.util.LinkedList","list":[{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1.1.1.1","matcherType":"DST_ADDR"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"80","matcherType":"DST_PORT"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1,3,2","matcherType":"DST_INTF"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"2.2.2.2","matcherType":"SRC_ADDR"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1,2,wan","matcherType":"SRC_INTF"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"UDP,TCP,any","matcherType":"PROTOCOL"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"svrbjgu","matcherType":"DIRECTORY_CONNECTOR_USERNAME"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"intern-it","matcherType":"DIRECTORY_CONNECTOR_GROUP"}]},"ruleId":5001,"javaClass":"com.untangle.node.firewall.FirewallRule","block":false,"log":true}]';
$data = json_decode($jsondata,true);
echo '<table><tr><th WIDTH="10">Nr.</th><th WIDTH="10">RuleID</th><th WIDTH="150">Description</th><th WIDTH="100">Protocol</th><th WIDTH="75">Src Int</th><th WIDTH="150">Src Address</th><th WIDTH="100">Src Port</th><th WIDTH="75">Dest. Int</th><th WIDTH="150">Dest Address</th><th WIDTH="100">Dest. Port</th><th WIDTH="50">Action</th><th WIDTH="50">Log</th><th WIDTH="50">Enabled</th></tr>';
echo "<tr><td>test.</td><td> {$data[0]['ruleId']} </td><td>{$data[0]['description']}</td><td>{$data[0]['enabled']}</td></tr>" ;
I have sth like that inside *.txt file.
function_name({"one": {"id": "id_for_one", "value": "value_for_one"}, ...});
And I am getting the file like this:
$source = 'FILE_NAME.txt';
$json = json_decode(file_get_contents($source),true);
echo $json['one']['value'];
It doesn't work, but when I remove function_name( and ); it works.
How to parse it without removing these strings?
You can't. It is not valid JSON with those. Take a substring that excludes them.
You will have to remove those strings. With the function_name portion it is not valid JSON.
A JSON string will typically either begin with { (object notation) or [ (array notation), but can also be scalar values such as a string or number. You cannot parse it without first making sure the string is valid JSON.
You are trying to get the string within a file and decoding it as a JSON file.
The 'function_name' isn't a valid JSON string, the rest inside yes.
How to parse it without removing these strings?
There is no way.
This should work for you.
$data = file_get_contents($source);
$data = substr($data, strlen("function_name("));
$data{strlen($data)-1}=$data{strlen($data)-2}=" ";
$json = json_decode($data,true);
Both {} and [] works for string to access individual characters.
The function in your text file, means that isn't a json file.
Remove the string using a regular expression, and your problem is fixed.
If the function is a fixed name, do something like this:
$source = 'FILE_NAME.txt';
$json_content = str_replace('function_name(', '', file_get_contents($source));
$json_content = substr($json_content,0,-2);
$json = json_decode($json_content,true);
echo $json['one']['value'];
This is a follow-up question to the one I posted here (thanks to mario)
Ok, so I have a preg_replace statement to replace a url string with sometext, insert a value from a query string (using $_GET["size"]) and insert a value from a associative array (using $fruitArray["$1"] back reference.)
Input url string would be:
http://mysite.com/script.php?fruit=apple
Output string should be:
http://mysite.com/small/sometext/green/
The PHP I have is as follows:
$result = preg_replace('|http://www.mysite.com/script.php\?fruit=([a-zA-Z0-9_-]*)|e', ' "http://www.mysite.com/" .$_GET["size"]. "/sometext/" .$fruitArray["$1"]. "/"', $result);
This codes outputs the following string:
http://mysite.com/small/sometext//
The code seems to skip the value in $fruitArray["$1"].
What am I missing?
Thanks!
Well, weird thing.
Your code work's perfectly fine for me (see below code that I used for testing locally).
I did however fix 2 things with your regex:
Don't use | as a delimiter, it has meaning in regex.
Your regular expression is only giving the illusion that it works as you're not escaping the .s. It would actually match http://www#mysite%com/script*php?fruit=apple too.
Test script:
$fruitArray = array('apple' => 'green');
$_GET = array('size' => 'small');
$result = 'http://www.mysite.com/script.php?fruit=apple';
$result = preg_replace('#http://www\.mysite\.com/script\.php\?fruit=([a-zA-Z0-9_-]*)#e', ' "http://www.mysite.com/" .$_GET["size"]. "/sometext/" .$fruitArray["$1"]. "/"', $result);
echo $result;
Output:
Rudis-Mac-Pro:~ rudi$ php tmp.php
http://www.mysite.com/small/sometext/green/
The only thing this leads me to think is that $fruitArray is not setup correctly for you.
By the way, I think this may be more appropriate, as it will give you more flexibility in the future, better syntax highlighting and make more sense than using the e modifier for the evil() function to be internally called by PHP ;-) It's also a lot cleaner to read, IMO.
$result = preg_replace_callback('#http://www\.mysite\.com/script\.php\?fruit=([a-zA-Z0-9_-]*)#', function($matches) {
global $fruitArray;
return 'http://www.mysite.com/' . $_GET['size'] . '/sometext/' . $fruitArray[$matches[1]] . '/';
}, $result);
i write it again, i don't understand good where is the error, the evaluation of preg results is very weird in php
preg_replace(
'|http\://([\w\.-]+?)/script\.php\?fruit=([\w_-]+)|e'
, '"http://www.$1/".$_GET["size"]."/sometext/".$fruitArray["$2"]."/";'
, $result
);
It looks like you have forgotten to escape the ?. It should be /script.php\?, with a \? to escape properly, as in the linked answer you provided.
$fruitArray["\$1"] instead of $fruitArray["$1"]