Regex for extract numbers and extension of string [closed] - php

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)

Related

Replace portion of css file content using preg_replace() [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 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.

Run a loop for each semicolon [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 3 years ago.
Improve this question
In my MySQL table I have a column with name "datei". For now each field contains a path - e.g. fileadmin/media/pdf/AGB.pdf
This is how my PHP looks like:
$Inhalt .= '<div class="DLB_Download_Zeile">
<a href="'.$Downloads->datei.'" target="_blank">
<div class="DLB_Download_Zeile_Bild"><img src="fileadmin/media/images/pdficon.png" width="30" alt="PDF Icon"></div>
<div class="DLB_Download_Zeile_Link">'.$Downloads->dateiname.'</div>
</a>
</div>';
I would now like to set the databse field to: fileadmin/media/pdf/AGB.pdf;fileadmin/media/pdf/anotherPDF.pdf;fileadmin/media/pdf/anotherFile.pdf
That mean in PHP I would need to run a loop that generates the same HTML for each path separated by the semicolon. How can I do this?
It would be possible to do using this:
$string = 'fileadmin/media/pdf/AGB.pdf;fileadmin/media/pdf/anotherPDF.pdf;fileadmin/media/pdf/anotherFile.pdf';
$paths = explode(';', $string);
foreach ($paths as $path) {
//Your code here
}
The explode() will split the sting at the semicolon's.
This can also be reversed to get a string again to put it in the database.
$string = implode(';', $paths);
You can try this :
$value = 'fileadmin/media/pdf/AGB.pdf;fileadmin/media/pdf/anotherPDF.pdf;fileadmin/media/pdf/anotherFile.pdf';
$array = explode(';', $value);
foreach ($array as $key => $value) {
echo $value;
}

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
}

php replace of keys inside a 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 8 years ago.
Improve this question
I have an array of keys and a medium/long string.
I need to replace only max 2 keys that I found in this text with the same keys wrapped with a link.
Thanks.
ex.:
$aKeys = array();
$aKeys[] = "beautiful";
$aKeys[] = "text";
$aKeys[] = "awesome";
...
$aLink = array();
$aLink[] = "http://www.domain1.com";
$aLink[] = "http://www.domain2.com";
$myText = "This is my beautiful awesome text";
should became "This is my <a href='http://www.domain1.com'>beautiful</a> awesome <a href='http://www.domain2.com'>text</a>";
Don't really understood what you need but you can do something like:
$aText = explode(" ", $myText);
$iUsedDomain = 0;
foreach($aText as $sWord){
if(in_array($sWord, $aKeys) and $iUsedDomain < 2){
echo "<a href='".$aLink[$iUsedDomain++]."'>".$sWord."</a> ";
}
else{ echo $sWord." "; }
}
So, you could use a snippet like this. I recommend you to update this code by using clean classes instead of stuff like global - just used this to show you how you could solve this with less code.
// 2 is the number of allowed replacements
echo preg_replace_callback('!('.implode('|', $aKeys).')!', 'yourCallbackFunction', $myText, 2);
function yourCallbackFunction ($matches)
{
// Get the link array defined outside of this function (NOT recommended)
global $aLink;
// Buffer the url
$url = $aLink[0];
// Do this to reset the indexes of your aray
unset($aLink[0]);
$aLink = array_merge($aLink);
// Do the replace
return ''.$matches[1].'';
}

must create a rule that captures the first preg_replace bar url [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
must create a rule that captures the first preg_replace bar url:
http://localhost/item/other
must take the rule just 'item' regardless of what comes after
You should use the php parse_url() function
An example would be:
$parts = parse_url("http://localhost/item/other");
$path_parts= explode('/', $parts[path]);
$item = $path_parts[1];
echo $item;
It does not look like you have a specific question. I am assuming you are about write some routes script.
$request_uri = explode('/', $_SERVER['REQUEST_URI']);
$delimiter = array_shift($request_uri);
$controller = array_shift($request_uri);
$action = array_shift($request_uri);
if(preg_match('/item/i', $controller))
{
// do something right
}
else
{
// do something wrong
}

Categories