Let's say I might have a couple of directories stored in a string.. they might look like this
/something/WHATEVER/websites/dev/tools/tests/media/upload.ini
/something/WHATEVER/websites/dev/tools/tests/get/add.ini
etc.
How can I extract the names "media" and "get" from those two links up there? I would probably have to use regular expressions but how would it look like?
Use php function explode? http://php.net/manual/en/function.explode.php
$str="one ,two , three , four ";
print_r(array_map('trim',explode(",",$str)));
Output:
Array ( [0] => one [1] => two [2] => three [3] => four )
If you want to use regexes, it might look like this
/([^/]+)/[^/]+$
i.e.,
preg_match('`/([^/]+)/[^/]+$`',$fullpath,$matches)
$matches[1] will contain your directory.
I would normally suggest sscanf for such easy patterns:
$string = '/something/WHATEVER/websites/dev/tools/tests/media/upload.ini';
$format = '/something/WHATEVER/websites/dev/tools/tests/%[^/]';
$r = sscanf($string, $format, $name);
Next to that there are standard PHP dirname functions that are helpful in case you need this more dynamic, e.g. the last directory name of a filename:
$string = '/something/WHATEVER/websites/dev/tools/tests/media/upload.ini';
$reduce = explode('/', dirname($string));
$name = end($reduce);
Demo
Related
I am trying to generate a regex that allows me to do the following:
I have a string containing several terms, all which are alphanumeric and maybe some of these special characters: +.#
They are separated by a comma as well.
This is kind of how it looks like:
$string = 'Term1,Term2,Term3,Term4'; ... And so on... (around 60 terms)
I want to be able to get each term and assign it to a variable, because I want to employ a second Regex to a long string, for example:
$secondString = 'This string may contain some terms, such as Term1, or maybe Term2';
So pretty much I want to be able to check if any of the terms in the first string are present in the second string.
I watched the following tutorial:
https://www.youtube.com/watch?v=EkluES9Rvak
But I just seem to not be able to come up with something.
Thank you so much for your help in advance!
Cheers!
You can use array_intersect function after splitting strings into tokens:
$string = 'Term1,Term2,Term3,Term4';
$secondString = 'This string may contain some terms, such as Term1, or maybe Term2';
$arr1 = explode(',', $string);
$arr2 = preg_split('/[,\h]+/', $secondString);
$arr = array_intersect(array_map('strtolower', $arr1), array_map('strtolower', $arr2));
print_r($arr);
Output:
Array
(
[0] => Term1
[1] => Term2
)
I am currently trying to create a random image generator in PHP, and I'm having a hard time setting the file path, I can get all the file paths, but they are in one long string, like this.
" ../images/box1/IMG_3158.JPG../images/box1/IMG_3161.JPG../images/box1/IMG_3163.JPG../images/box1/IMG_3158.JPG../images/box1/IMG_3161.JPG../images/box1/IMG_3163.JPG"
with the " .." marking the beginning of a new file.
How would i explode ( or something of the kind ) each file_path to return them separately?
Here is one way you can do this.
$data = '../images/box1/IMG_3158.JPG../images/box1/IMG_3161.JPG../images/box1/IMG_3163.JPG../images/box1/IMG_3158.JPG../images/box1/IMG_3161.JPG../images/box1/IMG_3163.JPG';
$files = preg_split('/(?<!^)(?=\.{2})/', $data);
print_r($files);
Output
Array
(
[0] => ../images/box1/IMG_3158.JPG
[1] => ../images/box1/IMG_3161.JPG
[2] => ../images/box1/IMG_3163.JPG
[3] => ../images/box1/IMG_3158.JPG
[4] => ../images/box1/IMG_3161.JPG
[5] => ../images/box1/IMG_3163.JPG
)
Regular Expression:
(?<! look behind to see if there is not:
^ the beginning of the string
) end of look-behind
(?= look ahead to see if there is:
\.{2} '.' (2 times)
) end of look-ahead
<?php
//Since new file path is starting from ".." we explode it using ".." and added to each file path.
$string ="../images/box1/IMG_3158.JPG../images/box1/IMG_3161.JPG../images/box1/IMG_3163.JPG../images/box1/IMG_3158.JPG../images/box1/IMG_3161.JPG../images/box1/IMG_3163.JPG";
$file_path=explode('..',$string);
$i=0;
while(isset($file_path[++$i])){
$file_path[$i]="..".$file_path[$i];
echo $file_path[$i]."<br />";
}
?>
http://ideone.com/MTRr9Q
Just use explode()
$file_paths = explode('..', $input);
Example
$string = "../images/box1/IMG_3158.JPG../images/box1/IMG_3161.JPG../images/box1/IMG_3163.JPG../images/box1/IMG_3158.JPG../images/box1/IMG_3161.JPG../images/box1/IMG_3163.JPG";
$file_paths = explode('..', $string);
var_dump($file_paths);
This strips of the ".." at the beginning, so try to append it yourself. For more complicated situations, a preg_split() would be an appropriate task. Given that your string doesn't change, then an explode could do.
If you are able to introduce an otherwise unused character between each path as you import(?) the list of path names, you could then use that character as your delimiter instead of ".." (refer to Ali's answer).
I have bunch of strings like this:
a#aax1aay222b#bbx4bby555bbz6c#mmm1d#ara1e#abc
And what I need to do is to split them up based on the hashtag position to something like this:
Array
(
[0] => A
[1] => AAX1AAY222
[2] => B
[3] => BBX4BBY555BBZ6
[4] => C
[5] => MMM1
[6] => D
[7] => ARA1
[8] => E
[9] => ABC
)
So, as you see the character right behind the hashtag is captured plus everything after the hashtag just right before the next char+hashtag.
I've the following RegEx which works fine only when I have a numeric value in the end of each part.
Here is the RegEx set up:
preg_split('/([A-Z])+#/', $text, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
And it works fine with something like this:
C#mmm1D#ara1
But, if I change it to this (removing the numbers):
C#mmmD#ara
Then it will be the result, which is not good:
Array
(
[0] => C
[1] => D
)
I've looked at this question and this one also, which are similar but none of them worked for me.
So, my question is why does it work only if it has followed by a number? and how I can solve it?
Here you can see some of them sample strings which I have:
a#123b#abcc#def456 // A:123, B:ABC, C:DEF456
a#abc1def2efg3b#abcdefc#8 // A:ABC1DEF2EFG3, B:ABCDEF, C:8
a#abcdef123b#5c#xyz789 // A:ABCDEF123, B:5, C:XYZ789
P.S. Strings are case-insensitive.
P.P.S. If you ever thinking what the hell are these strings, they are user submitted answers to a questionnaire, and I can't do anything on them like refactoring as they are already stored and just need to be proceed.
Why Not Using explode?
If you look at my examples you will see that I need to capture the character right before the # as well. If you think it's possible with explode() please post the output as well, thanks!
Update
Should we focus on why /([A-Z])+#/ works only if numbers included? thanks.
Instead of using preg_split(), decide what you want to match instead:
A set of "words" if followed by either <any-char># or <end-of-string>.
A character if immediately followed by #.
$str = 'a#aax1aay222b#bbx4bby555bbz6c#mmm1d#ara1e#abc';
preg_match_all('/\w+(?=.#|$)|\w(?=#)/', $str, $matches);
Demo
This expression uses two look-ahead assertions. The results are in $matches[0].
Update
Another way of looking at it would be this:
preg_match_all('/(\w)#(\w+)(?=\w#|$)/', $str, $matches);
print_r(array_combine($matches[1], $matches[2]));
Each entry starts with a single character, followed by a hash, followed by X characters until either the end of the string is encountered or the start of a next entry.
The output is this:
Array
(
[a] => aax1aay222
[b] => bbx4bby555bbz6
[c] => mmm1
[d] => ara1
[e] => abc
)
If you still want to use preg_split you can remove the + and it might work as expected:
'/([A-Z])#/i'
Since then you only match the hashtag and ONE alpha character before, and not all them.
Example: http://codepad.viper-7.com/z1kFDb
Edit: Added a case-insensitive flag i in the pattern.
Use explode() rather than Regexp
$tmpArray = explode("#","a#aax1aay222b#bbx4bby555bbz6c#mmm1d#ara1e#abc");
$myArray = array();
for($i = 0; $i < count($tmpArray) - 1; $i++) {
if (substr($tmpArray[$i],0,-1)) $myArray[] = substr($tmpArray[$i],0,-1);
if (substr($tmpArray[$i],-1)) $myArray[] = substr($tmpArray[$i],-1);
}
if (count($tmpArray) && $tmpArray[count($tmpArray) - 1]) $myArray[] = $tmpArray[count($tmpArray) - 1];
edit: I updated my answer to reflect better reading the questions
You can use explode() function that will split the string except the hash signs, like stated in the answers given before.
$myArray = explode("#",$string);
For the string 'a#aax1aay222b#bbx4bby555bbz6c#mmm1d#ara1e#abc' this returns something like
$myarray = array('a', 'aax1aay22b', 'bbx4bby555bbz6c' ....);
All you need now is to take the last character of each string in array as another item.
$copy = array();
foreach($myArray as $item){
$beginning = substr($item,0,strlen($item)-1); // this takes all characters except the last one
$ending = substr($item,-1); // this takes the last one
$copy[] = $beginning;
$copy[] = $ending;
} // end foreach
This is an example, not tested.
EDIT
Instead of substr($item,0,strlen($item)-1); you might use substr($item,0,-1);.
I have a string, /controller/method/parameter1/parameter2?parameter1=parameter2. This is just the REQUEST_URI I am using for my website.
I want to split this string into separate array elements using PHP, and the following code works fine for this action: preg_split('[/]', $_SERVER['REQUEST_URI'], NULL, PREG_SPLIT_NO_EMPTY).
This works almost perfectly, providing me with an excellent array output, until I add get variables. With these, the last array element includes the get variables too.
My question is, is there a way to stop processing as soon as a question mark (?) is reached?
I want to cut it from the question mark, and only show items before the question mark. This (hopefully) will mean that this:
Array
(
[0] => controller
[1] => method
[2] => parameter1
[3] => parameter2?parameter1=parameter2
)
Will become this:
Array
(
[0] => controller
[1] => method
[2] => parameter1
[3] => parameter2
)
The problem is, I want this all in the regular expression. I don't really care if there is another way (I know there is), I just want to know if there is a way to do this in the regex.
Thanks
Explode before split
$vars = explode('?', $_SERVER['REQUEST_URI']);
$array = preg_split('[/]', $vars[0], NULL, PREG_SPLIT_NO_EMPTY);
UPDATE
From php.net:
If you don't need the power of regular expressions, you can choose
faster (albeit simpler) alternatives like explode() or str_split().
In your case you can use str_split and save some time.
you can replace ?(.*) using:
preg_split('[/]',
preg_replace("/\?(.*)/", "", $_SERVER['REQUEST_URI']),
NULL, PREG_SPLIT_NO_EMPTY)
I do this in my system with strpos and substr before using regex:
$uri = $_SERVER['REQUEST_URI'];
$uri = ($pos = strpos($uri, '?')) ? substr($uri, 0, $pos) : $uri;
How could I Separate characters and numbers from an input and store as separate variables php for example my input string is as $str="abc567" and i need to separate it as $str1="abc" and $str2="567".
You can use preg_split using lookahead and lookbehind:
print_r(preg_split('#(?<=\d)(?=[a-z])#i', "abc567"));
prints
Array
(
[0] => abc
[1] => 567
)
I hope this helps :)
Regards.
By using preg_split, you can pass a regex string. This will return all the patterns that match a given regex string, and you can use that to store the various values into their respective variables.
Notice there is no code here; you should be trying to work these things out yourself.
well preg_split will help you.
Official Document : http://php.net/manual/en/function.preg-split.php
Example
echo "<pre>";
print_r(preg_split('#(?<=\d)(?=[a-z])#i', "abc567"));
echo "</pre>";
above will out put.
Array
(
[0] => abc
[1] => 567
)
try this
$str="abc567";
preg_match_all('/(\d)|(\w)/', $str, $matches);
$numbers = implode($matches[1]);
$characters = implode($matches[2]);
If your are wanting all numbers and all letters in separate variables you can use:
$your_var = "abc567";
$str_letters = preg_replace('/[a-z]/', "", $your_var);
$str_numbers = preg_replace('/[0-9]/', "", $your_var);
Beware that if $your_var = abc7567d64h num = 756764 letters = abcdh