In PHP I'm trying to strip information and store them in $sysver variable from a string named $freply like this:
var id='E8ABFA19FDE2';
var sys_ver='17.37.2.49';
var app_ver='20.9.1.150';
using PHP sscanf with whe following parameters:
sscanf($freply, "var sys_ver='%[^']'", $sysver);
However a blank result in $sysver is all I get.
UPDATE
Working on the first row with:
sscanf($freply, "var id=' %[^']'", $ea);
Gives me a correct result loaded as expected in $ea, that shows E8ABFA19FDE2.
Someone is able to tell me where's the mistake?
Despite I'm using PHP I guess this question is related to Javascript too or any other C-like language.
What you're telling sscanf() is your string is formatted beginning with the literal characters var sys_ver... etc. then you're passing it a string that starts with var id... and it's NOPE'ing right out.
This works:
sscanf($freply, "var id='E8ABFA19FDE2';\nvar sys_ver='%[^']'", $sysver);
or this:
foreach (explode("\n", $freply) as $line) {
if (sscanf($line, "var sys_ver='%[^']'", $sysver)) break;
}
But really sscanf() is not quite the right tool for this job. Just use preg_match():
preg_match("/var sys_ver='([^']+)'/", $freply, $matches);
$sysver = $matches[1];
Related
This is the code Im getting the error on:
$show_nav = preg_replace('#\{\$SUBMENU([0-9]+)\}#',implode("\n",$sub_menu['submenu$1']),$show_nav);
So basically I want to replace a string within the $show_nav variable such as {$SUBMENU2} with data from the sub menu array. I tested and it works just fine if I manually put in the number like so:
$show_nav = preg_replace('#\{\$SUBMENU([0-9]+)\}#',implode("\n",$sub_menu['submenu2']),$show_nav);
I also verified the regex is grabbing the proper variable by doing this:
$show_nav = preg_replace('#\{\$SUBMENU([0-9]+)\}#','$1',$show_nav);
It replaces the string with what is found in the {$SUBMENU} string. So if its {$SUBMENU3} it gives me back 3, {$SUBMENU5} it gives me back 5. But I cant seem to get it to dynamically read the $1 variable. I tried adding curly brackets, still same error:
$show_nav = preg_replace('#\{\$SUBMENU([0-9]+)\}#',implode("\n",$sub_menu['submenu{$1}']),$show_nav);
or:
$show_nav = preg_replace('#\{\$SUBMENU([0-9]+)\}#',implode("\n",$sub_menu['{submenu$1}']),$show_nav);
I know Im entering it wrong, but cant figure out the proper way of doing it. Any suggestions?
****UPDATE****
Thanks for the suggestions provided by Toto and Wiktor Stribiżew this is the code that resolved my issue, thanks again!!!
$show_nav = preg_replace_callback(
'#\{\$SUBMENU([0-9]+)\}#',
function($m) use($sub_menu) {
if(isset($sub_menu['submenu' .$m[1]]))
{
return '<ul class="nav-dropdown">' .implode("\n",$sub_menu['submenu' .$m[1]]) .'</ul>';
}
},$show_nav);
preg_replace_callback is your friend:
$show_nav = preg_replace_callback(
'#\{\$SUBMENU([0-9]+)\}#',
function($m) use($sub_menu) {
return implode("\n",$sub_menu['submenu'.$m[$1]])
},
$show_nav);
I want to remove all double quotes from a JSON file using PHP.
The following code outputs all the variables to a JSON file named example.json:
$var_geoJSON = 'var geoJSON = ';
file_put_contents('jsonfun.json', $var_geoJSON);
file_put_contents('jsonfun.json', json_encode($geojson, JSON_NUMERIC_CHECK), FILE_APPEND);
I was trying to get it to output something like this:
var geoJSON = {...}
Yet it outputs something like this:
"var geoJSON = " {...}
I am currently working with geoJSON to output to the open source leaflet.js mapping library, and the syntax requires that I have var geoJson = {...} instead of having "var geoJSON = "{...}.
I have tried using the PHP command preg_replace() replacing all the "" with spaces, yet that still didn't work and it outputted the same thing with the double quotes.
Any ideas?
Just use str_replace function http://www.w3schools.com/php/func_string_str_replace.asp example:
$result = str_replace('"', '', $json)
I would like to know if it's possible to execute the php code in a string. I mean if I have:
$string = If i say <?php echo 'lala';?> I wanna get "<?php echo 'dada'; ?>";
Does anybody knows how?
[EDIT] It looks like nobody understood. I wanna save a string like
$string = If i say <?php count(array('lala'));?>
in a database and then render it. I can do it using
function render_php($string){
ob_start();
eval('?>' . $string);
$string = ob_get_contents();
ob_end_clean();
return $string;
}
The problem is that I does not reconize php code into "" (quotes) like
I say "<?php echo 'dada'; ?>"
$string = ($test === TRUE) ? 'lala' : 'falala';
There are lots of ways to do what it looks like you're trying to do (if I'm reading what you wrote correctly). The above is a ternary. If the condition evaluates to true then $string will be set to 'lala' else set to 'falala'.
If you're literally asking what you wrote, then use the eval() function. It takes a passed string and executes it as if it were php code. Don't include the <?php ?> tags.
function dropAllTables() {
// drop all tables in db
}
$string = 'dropAllTables();';
eval($string); // will execute the dropAllTables() function
[edit]
You can use the following regular expression to find all the php code:
preg_match_all('/(<\?php )(.+?)( \?>)/', $string, $php_code, PREG_OFFSET_CAPTURE);
$php_code will be an array where $php_code[0] will return an array of all the matches with the code + <?php ?> tags. $php_code[2] will be an array with just the code to execute.
So,
$string = "array has <?php count(array('lala')); ?> 1 member <?php count(array('falala')); ?>";
preg_match_all('/(<\?php )(.+?)( \?>)/', $string, $php_code, PREG_OFFSET_CAPTURE);
echo $php_code[0][0][0]; // <?php count(array('lala')); ?>
echo $php_code[2][0][0]; // count(array('lala'));
This should be helpful for what you want to do.
Looks like you are trying to concatenate. Use the concatenation operator "."
$string = "if i say " . $lala . " I wanna get " . $dada;
or
$string = "if i say {$lala} I wanna get {$dada}.";
That is what I get since your string looks to be a php variable.
EDIT:
<?php ?> is used when you want to tell the PHP interpreter that the code in those brackets should be interpreted as PHP. When working within those PHP brackets you do not need to include them again. So as you would just do this:
// You create a string:
$myString = "This is my string.";
// You decide you want to add something to it.
$myString .= getMyNameFunction(); // not $myString .= <?php getMyNameFunction() ?>;
The string is created, then the results of getMyNameFunction() are appended to it. Now if you declared the $myString variable at the top of your page, and wanted to use it later you would do this:
<span id="myString"><?php echo $myString; ?></span>
This would tell the interpreter to add the contents of the $myString variable between the tags.
Use token_get_all() on the string, then look for a T_OPEN_TAG token, start copying from there, look for a T_CLOSE_TAG token and stop there. The string between the token next to T_OPEN_TAG and until the token right before T_CLOSE_TAG is your PHP code.
This is fast and cannot fail, since it uses PHP's tokenizer to parse the string. You will always find the bits of PHP code inside the string, even if the string contains comments or other strings which might contain ?> or any other related substrings that will confuse regular expressions or a hand-written, slow, pure PHP parser.
I would consider not storing your PHP code blocks in a database and evaluating them using eval. There is usually a better solution. Read about Design Pattern, OOP, Polymorphism.
You could use the eval() function.
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"]
I've got a jquery script, which creates a h3 tag and print a variable called result.tbUrl to it. I'd like to explode the variable at "::" and use the 2nd piece.
This is my method.
var link = document.createElement('h3');
link.innerHTML = <?php $link = "result.tbUrl"; $linkpiece = explode("::", $link); echo $pieces[1]; ?>;
Could you tell me please where did i make a mistake?
The first problem is, you're echoing $pieces[1], but exploding your string into $linkpiece which is a different variable.
However, you have a more serious problem: You're setting $link to the string "result.tbUrl". The string doesn't contain the delimiter '::', so exploding it has no effect and $linkpiece will be set to array(0 => 'result.tbUrl'). The line echo $linkpiece[1] will fail regardless, as there is nothing at index 1.
If result.tbUrl is a JavaScript variable, you cannot mix it with server-side PHP this way. You'll have to explode the variable client-side, in JavaScript:
var parts = result.tbUrl.split('::');
link.innerHTML = parts[1];