Regex extracting characters between last and second last occurance of character - php

i am trying to extract the word in between the last / and the second last / - i.e. food in the following PHP example.
$string = https://ss1.xxx/img/categories_v2/FOOD/fastfood (would like to replace $string to food)
$string = https://ss1.xxx/img/categories_v2/SHOPS/barbershop (would like to replace $string to shops)
I am new to regex and tried /[^/]*$ - however that is returning everying after the last /.. any help would be appreciated.. thanks!
I am using PHP.

Use:
preg_match('#/([^/]*)/[^/]*$#', $string, $match);
echo $match[1];
You could also use:
$words = explode('/', $string);
echo $words[count($words)-2];

You can use this:
$result = preg_replace_callback('~(?<=/)[^/]+(?=/[^/]*$)~', function ($m) {
return strtolower($m[0]); }, $string);
Pattern details:
~ # pattern delimiter
(?<=/) # zero width assertion (lookbehind): preceded by /
[^/]+ # all characters except / one or more times
(?=/[^/]*$) # zero width assertion (lookahead): followed by /,
# all that is not a / zero or more times, and the end of the string
~ # pattern delimiter

Regex:
(\w+)(/[^/]+)$
PHP code:
<?php
$string = "https://ss1.xxx/img/categories_v2/FOOD/fastfood";
echo preg_replace("#(\w+)(/[^/]+)$#", "food$2", $string);
$string = "https://ss1.xxx/img/categories_v2/SHOPS/barbershop";
echo preg_replace("#(\w+)(/[^/]+)$#", "shops$2", $string);
?>

Related

Php make spaces in a word with a dash

I have the following string:
$thetextstring = "jjfnj 948"
At the end I want to have:
echo $thetextstring; // should print jjf-nj948
So basically what am trying to do is to join the separated string then separate the first 3 letters with a -.
So far I have
$string = trim(preg_replace('/s+/', ' ', $thetextstring));
$result = explode(" ", $thetextstring);
$newstring = implode('', $result);
print_r($newstring);
I have been able to join the words, but how do I add the separator after the first 3 letters?
Use a regex with preg_replace function, this would be a one-liner:
^.{3}\K([^\s]*) *
Breakdown:
^ # Assert start of string
.{3} # Match 3 characters
\K # Reset match
([^\s]*) * # Capture everything up to space character(s) then try to match them
PHP code:
echo preg_replace('~^.{3}\K([^\s]*) *~', '-$1', 'jjfnj 948');
PHP live demo
Without knowing more about how your strings can vary, this is working solution for your task:
Pattern:
~([a-z]{2}) ~ // 2 letters (contained in capture group1) followed by a space
Replace:
-$1
Demo Link
Code: (Demo)
$thetextstring = "jjfnj 948";
echo preg_replace('~([a-z]{2}) ~','-$1',$thetextstring);
Output:
jjf-nj948
Note this pattern can easily be expanded to include characters beyond lowercase letters that precede the space. ~(\S{2}) ~
You can use str_replace to remove the unwanted space:
$newString = str_replace(' ', '', $thetextstring);
$newString:
jjfnj948
And then preg_replace to put in the dash:
$final = preg_replace('/^([a-z]{3})/', '\1-', $newString);
The meaning of this regex instruction is:
from the beginning of the line: ^
capture three a-z characters: ([a-z]{3})
replace this match with itself followed by a dash: \1-
$final:
jjf-nj948
$thetextstring = "jjfnj 948";
// replace all spaces with nothing
$thetextstring = str_replace(" ", "", $thetextstring);
// insert a dash after the third character
$thetextstring = substr_replace($thetextstring, "-", 3, 0);
echo $thetextstring;
This gives the requested jjf-nj948
You proceeding is correct. For the last step, which consists in inserting a - after the third character, you can use the substr_replace function as follows:
$thetextstring = 'jjfnj 948';
$string = trim(preg_replace('/\s+/', ' ', $thetextstring));
$result = explode(' ', $thetextstring);
$newstring = substr_replace(implode('', $result), '-', 3, false);
If you are confident enough that your string will always have the same format (characters followed by a whitespace followed by numbers), you can also reduce your computations and simplify your code as follows:
$thetextstring = 'jjfnj 948';
$newstring = substr_replace(str_replace(' ', '', $thetextstring), '-', 3, false);
Visit this link for a working demo.
Oldschool without regex
$test = "jjfnj 948";
$test = str_replace(" ", "", $test); // strip all spaces from string
echo substr($test, 0, 3)."-".substr($test, 3); // isolate first three chars, add hyphen, and concat all characters after the first three

PHP Regex matches beween Slash and Subtract

Hello I need a regex to get a string "trkfixo" from
SIP/trkfixo-000072b6
I was trying to use explode but I prefer a regex solution.
$ex = explode("/",$sip);
$ex2 = explode("-",$ex[1]);
echo $ex2[0];
You may use '~/([^-]+)~':
$re = '~/([^-]+)~';
$str = "SIP/trkfixo-000072b6";
preg_match($re, $str, $match);
echo $match[1]; // => trkfixo
See the regex demo and a PHP demo
Pattern details:
/ - matches a /
([^-]+) - Group 1 capturing 1 or more (+) symbols other than - (due to the fact that [^-] is a negated character class that matches any symbols other than all symbols and ranges inside this class).
$match = preg_match('/\/[a-zA-Z]-/', "SIP/trkfixo-000072b6");

Trouble With Regexp

I have to replace matches of patterns like <something:any-char> within a URL.
For example, a URL like this:
http://some-site.com/some-acion/pippo:1/mypar:asdasd/pippo2:sdd/ .....
should become:
http://some-site.com/some-acion/pippo:1/pippo2:sdd/ .....
In other words, I have to filter out any occurrence of mypar: from the URL.
I will use php for that.
I tried with RegExp:
.*[\/]+(sh:.*)[\/]?.*$
But it matches only strings like /pippo:3/mypar:wdfds. Strings like /pippo:2/mypar:asa/7pippo:1/ are not matched.
Any hint appreciated.
You could do this:
$url = "/pippo:2/mypar:asa/7pippo:1/";
$stripped = preg_replace("/\/mypar:.*?(\/|$)/", "$1", $url);
The combination of the lazy dot matching .*? with a positive lookahead (?=/|$) (either a / or the end of string) can be replaced with a mere any 0+ chars other than / with [^/]*:
'~/mypar:[^/]*~'
See the regex demo
The ~ delimiter makes it possible to use / in the pattern without escaping.
Pattern details:
/ - a forward slash
mypar: - a sequence of literal characters
[^/]* - zero or more characters other than / character
See PHP demo:
$re = '~/mypar:[^/]*~';
$str = "/pippo:2/mypar:asa/7pippo:1/";
$result = preg_replace($re, '', $str, 1);
echo $result;

CSS or PHP add space in number format

How can I add a space after 3 and 4 digits ?
I have this numbers: +4420719480
The result needs to be: +44 2071 9480
How can I add the spaces with css or php after 4 characters?
I have tried the following code:
$str = "+4420719480";
echo chunk_split($str, 4, ' ');
But how do I add the space to the first 3 characters and then to the 4th?
You can use preg_replace
$str = '+4420719480';
echo preg_replace('~^.{3}|.{4}(?!$)~', '$0 ', $str);
pattern explanation:
~ # pattern delimiter
^.{3} # any character 3 times at the start of the string
| # OR
.{4} # any character 4 times
(?!$) # not followed by the end of the string
~ # pattern delimiter
replacement: '$0 ' (the whole pattern and a space)
Sometimes the most mundane solution will do the job just fine.
$str = "+4420719480";
$new = substr($str,0,3).' '.substr($str,3,4).' '.substr($str,7);
Using your code, you can do:
$str = "+4420719480";
echo strrev(chunk_split(strrev($str),4," "));
Kinda clunky and only works for this size of $str, but it works!

return part of a string

I'm trying to return a certain part of a string. I've looked at substr, but I don't believe it's what I'm looking for.
Using this string:
/text-goes-here/more-text-here/even-more-text-here/possibly-more-here
How can I return everything between the first two // i.e. text-goes-here
Thanks,
$str="/text-goes-here/more-text-here/even-more-text-here/possibly-more-here";
$x=explode('/',$str);
echo $x[1];
print_r($x);// to see all the string split by /
<?php
$String = '/text-goes-here/more-text-here/even-more-text-here/possibly-more-here';
$SplitUrl = explode('/', $String);
# First element
echo $SplitUrl[1]; // text-goes-here
# You can also use array_shift but need twice
$Split = array_shift($SplitUrl);
$Split = array_shift($SplitUrl);
echo $Split; // text-goes-here
?>
The explode methods above certainly work. The reason for matching on the second element is that PHP inserts blank elements in the array whenever it starts with or runs into the delimiter without anything else. Another possible solution is to use regular expressions:
<?php
$str="/text-goes-here/more-text-here/even-more-text-here/possibly-more-here";
preg_match('#/(?P<match>[^/]+)/#', $str, $matches);
echo $matches['match'];
The (?P<match> ... part tells it to match with a named capture group. If you leave out the ?P<match> part, you'll end up with the matching part in $matches[1]. $matches[0] will contain the part with the forward slashes like "/text-goes-here/".
Just use preg_match:
preg_match('#/([^/]+)/#', $string, $match);
$firstSegment = $match[1]; // "text-goes-here"
where
# - start of regex (can be any caracter)
/ - a litteral /
( - beginning of a capturing group
[^/] - anything that isn't a litteral /
+ - one or more (more than one litteral /)
) - end of capturing group
/ - a litteral /
# - end of regex (must match first character of the regex)

Categories