Replace portion of css file content using preg_replace() [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 16 days ago.
Improve this question
$settings['new_primary_colour_ccs'] = '#777777'; // test color
foreach($appPats as $path){
$styleSettings = [
'primary_colour' => [
'reg' => "\bprimaryColour:\s?['\"][a-z0-9 ,._+;()'#!?&#:\/-]+['\"]",
'string' => "primaryColour: \"".$settings['new_primary_colour_ccs']."\"",
'value' => $settings['new_primary_colour_ccs']
]
];
foreach ($styleSettings as $style) {
$content = file_get_contents($path);
$result = preg_replace($style['reg'], $style['string'], $content);
file_put_contents($path, $result);
var_dump($result);
}
}
My css text looks like this:
(n["createcCommentVNode"])("",!0)],64)})),256))])):Object
(n["createCommentVNode"])("", !0)])]), Object(n["createELementVNode"])("div"
,me,[Object(n["createELementVNode"])("div",be,[X.config.EntryFormWithoutTime
?(Object(n["openBlock"])(),Object(n["createBlock"])(te,{key:0,onUpdated:e
.onUpdated,"is-new":"",modelValue:R.newEntry,"onUpdate:modelValue":t[0]||
(t[0]=function(e){return R.newEntry=e})},null,8,["onUpdated","modelValue"]
)):(Object(n["openBlock"])(),Object(n["createBlock"])(xe,{key:1,onUpdated:e
.onUpdated,"is-new":"",modelValue:R.newEntry,"onUpdate:modelValue":t[1]||
(t[1]=function(e){return R.newEntry=e})},null,8,["onUpdated","modelValue"]
))])])],64)}a("498a"),a("acl1f"),a("5319"),a("a434");var ge={client:"Rail
Partners",showWelcomeMessage:!1,logo:"https: //1wee.webx.host/images
/RP_Logo_Black.svg",LogoWidth:124,LogoMargin:"10px 0 10px 0"
,navBackgroundColour:"rgb(36, 142, 120)",navShowWave:!1,colourScheme:"blue"
,bodyBackgroundImage:!1,bgColour:"#FFFFFF",primaryColour:"#AD9DF4",url
:"https://1wee.webx.host",enableAcademy:!0,enableScheduler:!0
,homepageDispLayVehicLeChart:!1,calendarDispLayNameOn1ly:!0
,caLendarMonthyDefaultSort:"name",EntryFormWithoutTime:!0
,caLendarAnnualLeaveCatId:25,calendarRemainingTimeLeftShownInHours:!0
,notificationEmailId:26,userProfile:{profileImgId:3,width:400,height:400
,quality:100}},fe=a("a18a"),ke=a.n(fe),ve={class:"uk-text-center uk-width
-large uk-align-center"},ye=Object(n["createELementVNode"])("img",{class:"uk
I need to change my css style using preg_replace

From what I see, you need to apply pattern delimiters and case-insensitivity. See the ~ delimiting characters on the outside of the pattern and the trailing i to signify that case-insensitivity should be used by the regex engine (because the hex color code is in all-caps).
Also, you should avoid needlessly fetching and saving the same content over and over. Instead, fetch the file content once, do all the processing, then save it once.
Code: (Demo)
$settings['new_primary_colour_ccs'] = '#777777'; // test color
foreach ($appPats as $path) {
$styleSettings = [
'primary_colour' => [
'reg' => "~\bprimaryColour:\s?['\"][a-z0-9 ,._+;()'#!?&#:\/-]+['\"]~i",
'string' => 'primaryColour:"' . $settings['new_primary_colour_ccs'] . '"',
'value' => $settings['new_primary_colour_ccs']
]
];
$content = file_get_contents($path);
foreach ($styleSettings as $style) {
$content = preg_replace($style['reg'], $style['string'], $content);
}
file_put_contents($path, $content);
}
If in your actual application, $styleSettings doesn't change inside the parent loop, move the declaration above that loop. It doesn't make sense to keep re-declaring it with the same data.

Related

How do i make all the ' symbols into " while still detecting the variables in PHP? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
So I have this peice of code, the function is not relavant for the question
Samplefunction("fileDirectory", 23, "{ 'title': '.$PageTitle', 'url': '/.$PageTitle/' },");
In the row in bold, the line: "{ 'title': '.$PageTitle', 'url': '/.$PageTitle/' }," is a good and working line. however since this is a sting in a function, currently the ' symbols have to be ".
If i writ the line like so:
'{ "title": ".$PageTitle", "url": "/.$PageTitle/" },');
The string will be ok but the variables will be undetected.
I need the string within to a " and not a ' but i also need the variables to be detected.
Any suggestions on how to do this?
Best Regards,
AT
My complete code:
$filedirectory = "/sample/file/directoy";
$PageTitle = "shop";
function textinjector($file, $linerNumber, $injText ) {
$content = file($file); //Read the file into an array. Line number => line content
foreach($content as $lineNumber => &$lineContent) { //Loop through the array (the "lines")
if($lineNumber == $linerNumber) { //Remember we start at line 0.
$lineContent .= $injText . PHP_EOL; //Modify the line. (We're adding another line by using PHP_EOL)
}
}
$allContent = implode("", $content); //Put the array back into one string
file_put_contents($file, $allContent); //Overwrite the file with the new content
echo "$injText was injected to $file at line number $lineNumber";
}
// insertTextAtLineNumber("$filedirectory", 20, "import $pagetitlecaps from './$PageTitle/index';");
textinjector("$filedirectory", 23, '{ "title": ".$PageTitle", "url": "/.$PageTitle/" },'); // inject text into the menu area
?>
You can change the way you generate the string by breaking the it up in to the separate parts (static and dynamic) and concatenating the parts together with .
textinjector($filedirectory, 23, '{ "title": ".' . $PageTitle . '", "url": "/.' . $PageTitle . '/" },');

Regex for extract numbers and extension of string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I use code below for extract numbers and file name of strings with problem standardization
30183308__90_.jpeg
30193253-(100).jpg
30193253__100__.jpg
30193253_ _100_ _.jpg
Use this function
public function refactorFileName($filename)
{
$array = preg_split("/[^A-Za-z0-9]/", $filename);
foreach($array as $key => $value) {
if($value == "") {
unset($array[$key]);
}
}
$array = array_values($array);
$standardFilename = $array[0].'.'.$array[2];
$indexFile = $array[1];
return compact("indexFile","standardFilename");
}
$filename = '30193253_ _100_ _.jpg';
extract(refactorFileName($filename));
echo "New File name -> ".$standardFilename.PHP_EOL;
echo "Index for file -> ".$indexFile.PHP_EOL;
This show (correct):
New File name -> 30193253.jpg
Index for file -> 100
I think there're a better code for regex expresion.
EDIT:
It's possible better code on preg_split or better code in general for this question?
Two things: 1) It will be easier if you put a quantifier in your pattern (to avoid the useless foreach after). (Note that preg_split has also the option PREG_SPLIT_NO_EMPTY to avoid empty items.)
2) sometimes too much verbosity kills the verbosity.
Your can rewrite it this way:
function refactorFileName($filename) {
$p = preg_split('~[\W_]+~', $filename, 3);
return [ 'indexFile' => $p[1], 'standardFilename' => "$p[0].$p[2]" ];
}
Or if you want to be more verbose:
function refactorFileName($filename) {
list($name, $index, $ext) = preg_split('~[\W_]+~', $filename, 3);
return [ 'indexFile' => $index, 'standardFilename' => "$name.$ext" ];
}
(As an aside, when you already have a working code, ask your question on codereview instead of SO)

How to match div content which has divs inside by using regex [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Content is
<html>...<div id="endText" class="end-text" jcid="8311"><p>Hello</p>World<div class="ep-source cDGray"></div></div>...</html>
How to match
<p>Hello</p>World<div class="ep-source cDGray"></div>
Thank you!
#Rizier123
$content = '';
if(preg_match('/"endText".+?>.+?(?=<div.+?class="ep-source cDGray">)/i', $html, $contents) &&
preg_match('/(?<=>).+/i', $contents[0], $contentss))
{
$content = iconv('GBK', 'UTF-8', $contentss[0]);
return rtrim('OK' . "\t" . $content);
}
else
{
return rtrim('SKIP' . "\t" . 'NO_CONTENT');
}
This method can be used temporary, can't solve the problem.
Just match and remove the first-level div.
Regex (matches the opening div, saves its innards, and matches the last closing div):
/^<div id="endText"[^>]+>(.*?)<\/div>$/ism
PHP example:
preg_match('/^<div id="endText"[^>]+>(.*?)<\/div>$/ism', $html, $contents);
echo $contents[1];
// returns: <p>Hello</p>World<div class="ep-source cDGray"></div>
Adding the id attribute to the regex helps to specify that particular div

Reliably retrieve PHP constant from a file [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Latest Edit:
Well, I came up with fairly "reliable" :) solution in form of a (portable) function, but since some ppl here got irked enough by not understanding the problem and blocked this question (a military solution: kill what you do not understand), I cannot post it here. Pity.
I have a set of files, which contain constants, like below.
define ('LNG_GSU_LNK_LBL', '[details]');
define( 'LNG_METHODCROSS_GSU_CLS' ,'class');
define('GSU_METH' , 'method');
define ( 'CROSS_GSU_ACTION_NO_REMOVE', 'cannot remove \' module \'(is); deployed');
What would be most reliable method to retrieve constant names and values from given, selected file.
EDIT:
I need to get these constants into array, without defining them actually, directly by reading file, e.g.:
array('LNG_GSU_LNK_LBL'=>'[details]','LNG_METHODCROSS_GSU_CLS'=> 'class')
... etc
EDIT 2:
So far I got this far:
$file_array = file($path, FILE_SKIP_EMPTY_LINES);
//implode lang file into a string removing php tags
$string1 = implode('', $file_array);
$string2 = str_replace(array(''), '', $string1);
//regex removing content between markers
$regex = '/\/\*.+?\*\//si';
$replace_with = '';
$replace_where = $string2;
$string3 = preg_replace($regex, $replace_with, $replace_where);
//regex: remove multiple newlines
$string4 = preg_replace("/\n+/", "\n", $string3);
EDIT 3:
expected result
array (
'LNG_GSU_LNK_LBL' => '[details]',
'LNG_METHODCROSS_GSU_CLS' => 'class',
'GSU_METH' => 'method',
'CROSS_GSU_ACTION_NO_REMOVE' => 'cannot remove \' module \'(is); deployed'
);
If you dont want to include the file, then you should use: token_get_all().
Otherwise, you should require/include the file containing them and you can iteratively use get_defined_constants():
$all = array();
$consts = get_defined_constants();
foreach($consts as $k=>$v){
if (strpos($k,"LNG")===0 && !isset($all[$k]))
$all[$k]=$v;
}
Note that parsing php source code is like parsing HTML with regex, better bet avoid it.
Building on dynamic's answer, include the file within another, separate, web accessible file, that is not loaded within your current application (so will have no other user defined constants at run time):
//standalone.php
include "that_file.php";
$consts = get_defined_constants(true);
$newUserConsts = $consts['user'];
echo json_encode($newUserConsts);
//within your application
$newUserConsts = json_decode(file_get_contents('http://yoursite.com/standalone.php'));
Or if you cant make a separate web accessible file:
$consts = get_defined_constants(true);
$existingUserConsts = $consts['user'];
include "that_file.php";
$consts = get_defined_constants(true);
$newUserConsts = $consts['user'];
var_dump(array_diff_key($newUserConsts, $existingUserConsts));

How to separate text with PHP [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Well I am trying to make a simple php system.
Anywise I need to separate the text when I want to add it to the database.
So for example I want to add:
abc:123
I want that the : will be the separater, so it'll look like this:
abc
123
And then both will go to a different table.
Could someone help me with this? As I am not an experience PHP coder, yet I am willing to learn how to do this.
Kind regards
This is pretty basic stuff..
$data = explode(':','abc:123');
foreach($data as $word)
{
// some code here
}
Use Split:
<?php
$data = "abc:123";
list ($var1, $var2) = split (':', $data);
echo "Var1: $var1; Var2: $var2;<br />\n";
?>
You can achieve this using explode.
abc:123
Is a string. Let's define it as a variable:
$origin = "abc:123";
You can split the string, using : as the separator.
$separator = ":";
$exploded = explode($separator, $origin);
Now you have an array which you can use to access abc and 123 individually.
$pre = $exploded[0];
$post = $exploded[1];
You don't know how many splits there will be?
That's okay. Your array simply increases, meaning you can simply loop through the array and handle the values.
foreach ($exploded as $split)
{
// Do something with $split
}

Categories