PHP Regex Question - php

Would it be possible to make a regex that reads {variable} like <?php echo $variable ?> in PHP files?
Thanks
Remy

The PHP manual already provides a regular expression for variable names:
[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
You just have to alter it to this:
\{[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\}
And you’re done.
Edit   You should be aware that a simple sequential replacment of such occurrences as Ross proposed can cause some unwanted behavior when for example a substitution also contains such variables.
So you should better parse the code and replace those variables separately. An example:
$tokens = preg_split('/(\{[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\})/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
for ($i=1, $n=count($tokens); $i<$n; $i+=2) {
$name = substr($tokens[$i], 1, -1);
if (isset($variables[$name])) {
$tokens[$i] = $variables[$name];
} else {
// Error: variable missing
}
}
$string = implode('', $tokens);

It sounds like you're trying to do some template variable replacement ;)
I'd advise collecting your variables first, in an array for example, and then use something like:
// Variables are stored in $vars which is an array
foreach ($vars as $name => $value) {
$str = str_replace('{' . $name . '}', $value, $str);
}

{Not actually an answer, but need clarification}
Could you expand your question? Are you wanting to apply a regex to the contents of $variable?

The following line should replace all occurences of the string '{variable}' with the value of the global variable $variable:
$mystring = preg_replace_callback(
'/\{([a-zA-Z][\w\d]+)\}/',
create_function('$matches', 'return $GLOBALS[$matches[1]];'),
$mystring);
Edit: Replace the regex used here by the one mentioned by Gumbo to precisely catch all possible PHP variable names.

(in comments) i want to be able to type {variable}
instead of <?php echo $variable ?>
Primitive approach: You could use an external program (e.g. a Python script) to preprocess your files, making the following regex substitution:
"{([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)}"
with
"<?php echo $\g<1> ?>"
Better approach: Write a macro in your IDE or code editor to automatically make the substitution for you.

Related

PHP preg_replace string with value of variable

I am trying to use regex in php to find all strings that starts with "$" and replacing it with the appropriate variable. For example:
$value = "Some Value";
<b>$value</b>
Where the end result should be:
<b>Some Value</b>
This is what I have tried:
ob_start("tagreplace");
function tagreplace ( $tagreplace )
{
$value1 = "Some Value";
$pattern = '/(?<=\s)(\$[^#\s]+)(?=\s)/';
$tagreplace = preg_replace( $pattern , '<?php echo $0 ?>', $tagreplace);
return $tagreplace;
}
/* html files for combining */
include 'main_content.html';
ob_end_flush();
But this doesn't seem to work... I've tried for loops, while loops, and none of them are working. Basically I am trying to be extremely lazy and use regex to make very shorthand variables that I can put everywhere, replacing the strings like "$value" with whatever corresponding value that the variable $value has assigned to it.
I understand that /e is now deprecated so I can't use that to treat php tags as actual code. I have attempted to use preg_replace_callback but this didn't actually do anything. I'm thinking there probably isn't a way to properly do this.
It's not exactly clear what you're trying to do here, although if you take a slightly different approach with your regex you'll likely have more success. Essentially it's easier to break the pattern up into three capture groups (the start tag, the value, and the end tag)
function tagreplace ( $tagreplace ) {
$replace = "Some Value";
$pattern = '/(.+>)(.+)(<.+)/m';
$tagreplace = preg_replace( $pattern, '$1'.$replace.'$3', $tagreplace);
return $tagreplace;
}
$value = "Old Value";
echo tagreplace("<b>$value</b>");
echo "\n -- Using \$value slightly different-- \n";
$value = "<b>$value</b>";
echo tagreplace($value);
By using a more generic pattern you should be able swap out $value, regardless if it's the entire value, or if it's what is between the < > tags. When in doubt use a regex tester (linked below) and you might be able to eliminate several recursive loops, or going around in circles.
Example:
https://regex101.com/r/rW8lC6/1

Regex use replaced string replacement

I have strings like this
[Ljava.lang.String;
[Ldummy.class.Here;
[Lanother.unknown.Class;
What regex should i use to replace [L and ; with <span>,[]</span>
And make it look like this
<span>java.lang.String[]</span>
<span>dummy.class.Here[]</span>
<span>another.unknown.Class[]</span>
What i want is to make java array class string representation more human friendly
I've heard about $1 or something like that, but i couldn't find more information as i don't know what is it
$strings = "[Ljava.lang.String;
[Ldummy.class.Here;
[Lanother.unknown.Class;";
$strings = preg_replace('/\[L([A-Za-z\.]+);/', '<span>$1[]</span>', $strings);
echo $strings;
Output:
$ php foo.php
<span>java.lang.String[]</span>
<span>dummy.class.Here[]</span>
<span>another.unknown.Class[]</span>
If you want to use plain old PHP for this rather than a regex, here is a simple snippet that will do exactly what you need - and you can modify it without having to sort through regex that makes little sense to you:
<?php
$stringArray=array(
'[Ljava.lang.String;',
'[Ldummy.class.Here;',
'[Lanother.unknown.Class;'
);
foreach($stringArray as $val)
{
$output=$val;
if($val[0].$val[1]=='[L')
{
$output="<span>".substr($val,2);
}
if(substr($output,-1)==';')
{
$output=substr($output,0,strlen($output)-1).'</span>';
}
echo $output.'<br>';
}
?>
Output:
<span>java.lang.String</span>
<span>dummy.class.Here</span>
<span>another.unknown.Class</span>
This should do it:
$new_content = preg_replace('#^\[L(.*);\s*$#m', '<span>$1[]</span>', $content);
Demo here: http://sandbox.onlinephpfunctions.com/code/8f0de08b5ba0882db2d98d99cdd961b9aebab074
You can use this:
$result = preg_replace('~\[L([^;]+);~', '<span>$1[]</span>', $txt);
where [^;]+ matches all that is not a ";"

parsing inline variables from string from file in php

I'm localizing a website that I've built. I'm doing this by having a .lang file read and each line (syntax: key=string) is placed in a variable depending on the chosen language.
This array is then used to place the strings in the correct places.
The problem I'm having is that certain strings need to have hyperlinks in the middle of them for example someplace I've put my name that links to my contact page. Or a lot of the readouts of the website need to be in the strings.
To solve this I've defined a variable that holds the html + Forecaster + html,
and the localization file contains the $Forecaster variable in the string.
The problem with this as I promptly discovered is that it stubbornly refuses to parse the inline variables in the strings from the file.
Instead it prints the string and variable name as it looks in the file.
And I have yet to find a way to make it parse the variables.
For example "Heating up took $str_time" would be printed on the page exactly like that, instead of inputting the previously defined value of $str_time.
I currently use fopen() and fgets() to open and read the lines. I then explode them to separate the key and the string and then place these into the array.
Is there a way to make it parse the variables, or alternatively is there another way of reading the lines that allows for parsing the inline variables?
The code that gets the line and converts it to the array looks like this:
(It obviously loops through the lines)
#list($key, $string) = explode('=', $line);
$key = strtok($line, '=');
$string = strtok('=');
$local[$key] = $string;
$counter++;
echo $local[$key] . "<br>";
The counter is unused and the echo is for testing.
A line from the .lang file looks like this:
fuel.results.heatup.timeused=Heating up took $str_time
I would call the array where I want the string like this:
$local['fuel.results.heatup.timeused']
As you can see I've tried both explode and strtok but it hasn't made a difference.
Personally I'd write your text file in JSON format to make it easier to pull data out.
Here is a solution directly from the php manual: http://nz2.php.net/manual/en/function.eval.php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
It is worth noting that eval() can be very dangerous used in the wrong way so make sure you're code is very secure E.g. if someone altered your txt file with real PHP code they could execute it directly on the server.
Another approach would require you to know all your variable names and could then do something like:
$str = 'Heating up took $str_time';
echo 'str=' . str_replace('$str_time', $str_time, $str);
Or do this via an array:
$str = 'Heating up took $str_time as well as $other_value';
$vars = Array('str_time', 'other_value');
foreach($vars as $varName) {
$str = str_replace('$' . $varName, $$varName, $str);
}
echo 'str=' . $str;
If you not know all the variable name, you can use this example, without eval(). It is indicatred to avoid eval().
$str = 'fuel.results.heatup.timeused=Heating up took $str_time';
$str_time = 'value';
if(preg_match('/\$([a-z0-9_]+)/i', $str, $v)) {
$vname = $v[1];
$str = str_replace('$'.$vname, $$vname, $str);
}
echo $str; // fuel.results.heatup.timeused=Heating up took value

I need to get a value in PHP "preg_match_all" - Basic (I think)

I am trying to use a License PHP System…
I will like to show the status of their license to the users.
The license Server gives me this:
name=Service_Name;nextduedate=2013-02-25;status=Active
I need to have separated the data like this:
$name = “Service_Name”;
$nextduedate = “2013-02-25”;
$status = “Active”;
I have 2 days tring to resolve this problem with preg_match_all but i cant :(
This is basically a query string if you replace ; with &. You can try parse_str() like this:
$string = 'name=Service_Name;nextduedate=2013-02-25;status=Active';
parse_str(str_replace(';', '&', $string));
echo $name; // Service_Name
echo $nextduedate; // 2013-02-25
echo $status; // Active
This can rather simply be solved without regex. The use of explode() will help you.
$str = "name=Service_Name;nextduedate=2013-02-25;status=Active";
$split = explode(";", $str);
$structure = array();
foreach ($split as $element) {
$element = explode("=", $element);
$$element[0] = $element[1];
}
var_dump($name);
Though I urge you to use an array instead. Far more readable than inventing variables that didn't exist and are not explicitly declared.
It sounds like you just want to break the text down into separate lines along the semicolons, add a dollar sign at the front and then add spaces and quotes. I'm not sure you can do that in one step with a regular expression (or at least I don't want to think about what that regular expression would look like), but you can do it over multiple steps.
Use preg_split() to split the string into an array along the
semicolons.
Loop over the array.
Use str_replace to replace each '=' with ' = "'.
Use string concatenation to add a $ to the front and a "; to the end of each string.
That should work, assuming your data doesn't include quotes, equal signs, semicolons, etc. within the data. If it does, you'll have to figure out the parsing rules for that.

filter specific string in php

$var="UseCountry=1
UseCountryDefault=1
UseState=1
UseStateDefault=1
UseLocality=1
UseLocalityDefault=1
cantidad_productos=5
expireDays=5
apikey=ABQIAAAAFHktBEXrHnX108wOdzd3aBTupK1kJuoJNBHuh0laPBvYXhjzZxR0qkeXcGC_0Dxf4UMhkR7ZNb04dQ
distancia=15
AutoCoord=1
user_add_locality=0
SaveContactForm=0
ShowVoteRating=0
Listlayout=0
WidthThumbs=100
HeightThumbs=75
WidthImage=640
HeightImage=480
ShowImagesSystem=1
ShowOrderBy=0
ShowOrderByDefault=0
ShowOrderDefault=DESC
SimbolPrice=$
PositionPrice=0
FormatPrice=0
ShowLogoAgent=1
ShowReferenceInList=1
ShowCategoryInList=1
ShowTypeInList=1
ShowAddressInList=1
ShowContactLink=1
ShowMapLink=1
ShowAddShortListLink=1
ShowViewPropertiesAgentLink=1
ThumbsInAccordion=5
WidthThumbsAccordion=100
HeightThumbsAccordion=75
ShowFeaturesInList=1
ShowAllParentCategory=0
AmountPanel=
AmountForRegistered=5
RegisteredAutoPublish=1
AmountForAuthor=5
AmountForEditor=5
AmountForPublisher=5
AmountForManager=5
AmountForAdministrator=5
AutoPublish=1
MailAdminPublish=1
DetailLayout=0
ActivarTabs=0
ActivarDescripcion=1
ActivarDetails=1
ActivarVideo=1
ActivarPanoramica=1
ActivarContactar=1
ContactMailFormat=1
ActivarReservas=1
ActivarMapa=1
ShowImagesSystemDetail=1
WidthThumbsDetail=120
HeightThumbsDetail=90
idCountryDefault=1
idStateDefault=1
ms_country=1
ms_state=1
ms_locality=1
ms_category=1
ms_Subcategory=1
ms_type=1
ms_price=1
ms_bedrooms=1
ms_bathrooms=1
ms_parking=1
ShowTextSearch=1
minprice=
maxprice=
ms_catradius=1
idcatradius1=
idcatradius2=
ShowTotalResult=1
md_country=1
md_state=1
md_locality=1
md_category=1
md_type=1
showComments=0
useComment2=0
useComment3=0
useComment4=0
useComment5=0
AmountMonthsCalendar=3
StartYearCalendar=2009
StartMonthCalendar=1
PeriodOnlyWeeks=0
PeriodAmount=3
PeriodStartDay=1
apikey=ABQIAAAAJ879Hg7OSEKVrRKc2YHjixSmyv5A3ewe40XW2YiIN-ybtu7KLRQiVUIEW3WsL8vOtIeTFIVUXDOAcQ
";
in that string only i want "api==ABQIAAAAJ879Hg7OSEKVrRKc2YHjixSmyv5A3ewe40XW2YiIN-ybtu7KLRQiVUIEW3WsL8vOtIeTFIVUXDOAcQ";
plz guide me correctly;
EDIT
As shamittomar pointed out, the parse_str will not work for this situation, posted the proper regex below.
Given this seems to be a QUERY STRING, use the parse_str() function PHP provides.
UPDATE
If you want to do it with regex using preg_match() as powertieke pointed out:
preg_match('/apikey=(.*)/', $var, $matches);
echo $matches[1];
Should do the trick.
preg_match(); should be right up your alley
people are so fast to jump to preg match when this can be done with regular string functions thats faster.
$string = '
expireDays=5
apikey=ABQIAAAAFHktBEXrHnX108wOdzd3aBTupK1kJuoJNBHuh0laPBvYXhjzZxR0qkeXcGC_0Dxf4UMhkR7ZNb04dQ
distancia=15
AutoCoord=1';
//test to see what type of line break it is and explode by that.
$parts = (strstr($string,"\r\n") ? explode("\r\n",$string) : explode("\n",$string));
$data = array();
foreach($parts as $part)
{
$sub = explode("=",trim($part));
if(!empty($sub[0]) || !empty($sub[1]))
{
$data[$sub[0]] = $sub[1];
}
}
and use $data['apikey'] for your api key, i would also advise you to wrpa in function.
I can bet this is a better way to parse the string and much faster.
function ParsemyString($string)
{
$parts = (strstr($string,"\r\n") ? explode("\r\n",$string) : explode("\n",$string));
$data = array();
foreach($parts as $part)
{
$sub = explode("=",trim($part));
if(!empty($sub[0]) || !empty($sub[1]))
{
$data[$sub[0]] = $sub[1];
}
}
return $data;
}
$data = ParsemyString($string);
First of all, you are not looking for
api==ABQIAAAAJ879Hg7OSEKVrRKc2YHjixSmyv5A3ewe40XW2YiIN-ybtu7KLRQiVUIEW3WsL8vOtIeTFIVUXDOAcQ
but you are looking for
apikey=ABQIAAAAJ879Hg7OSEKVrRKc2YHjixSmyv5A3ewe40XW2YiIN-ybtu7KLRQiVUIEW3WsL8vOtIeTFIVUXDOAcQ
It is important to know if the api-key property always occurs at the end and if the length of the api-key value is always the same. I this is the case you could use the PHP substr() function which would be easiest.
If not you would most probably need a regular expression which you can feed to PHPs preg_match() function. Something along the lines of apikey==[a-zA-Z0-9\-] Which matches an api-key containing a-z in both lowercase and uppercase and also allows for dashes in the key. If you are using the preg_match() function you can retrieve the matches (and thus your api-key value).

Categories