/ (slash) in preg_match - php

I have this section some/aaa/9321/something from which I want to extract only 9321. "something" always differs, "aaa" is alyways static. So, I used:
$text = "something/aaa/9321/something";
$first = 'aaa/';
$after = '/';
preg_match("/$first(.*)$after/s",$text,$result);
echo $result;
But isn't working. Can somebody please tell me what I need to use?
I've tried this too:
$text = "something/aaa/9321/something";
$first = 'aaa';
preg_match("|$first(.*)|",$text,$result);
echo substr($result['1'], 1, 4);
But between aaa and something not always 4 characters.
Sorry for bad english. Thanks!

You should always preg_quote strings when you want them to be taken literally in a regular expression:
$text = 'something/aaa/9321/something';
$first = preg_quote('aaa/', '/');
$after = preg_quote('/', '/');
preg_match("/$first(.*)$after/s",$text,$result);
echo $result[1]; // '9321'
Demo
The problem was caused by the fact that / is the delimiter in your regex. You could have also solved this problem by using a different delimiter, such as ~, however, you would just run into the same problem as soon as your string had a ~ or any other character with a special meaning like ., or ?. By using preg_quote, you won't run into this problem again.

Have you tried escaping the /?
Instead of
$first = 'aaa/';
$after = '/';
try
$first = 'aaa\/';
$after = '\/';

Related

Find a string that is not always the same [PHP]

I need help finding something in a variable that isn't always the same, and then put it in another variable.
I know that what I'm looking for has 5 slashes, it starts with steam://joingame/730/ and after the last slash there are 17 numbers.
Edit: It doesn't end with a slash, thats why I need to count 17 numbers after the fifth slash
Assuming what you're looking for looks something like this:
steam://joingame/730/11111111111111/
Then you could use explode() as a simple solution:
$gameId = explode('/', 'steam://joingame/730/11111111111111/');
var_dump($gameId[4]);
or you could use a regex as a more complex solution:
preg_match('|joingame/730/([0-9]+)|', 'steam://joingame/730/11111111111111/', $match);
var_dump($match[1]);
This splits the string into an array then return the last element as the game_id. It doesn't matter how many slashes. It will always return the last one.
$str = 'steam://joingame/730';
$arr = explode("/", $str) ;
$game_id = end($arr);
Following on from what DragonSpirit said
I modified there code so the string can look like
steam://joingame/730/11111111111111
or
steam://joingame/730/11111111111111/
$str = 'steam://joingame/730/11111111111111/';
$rstr = strrev( $str ); // reverses the string so it is now like /1111111111...
if($rstr[0] == "/") // checks if now first (was last ) character is a /
{
$nstr = substr($str, 0, -1); // if so it removes the /
}
else
{
$nstr = $str; // else it dont
}
$arr = explode("/", $nstr) ;
$game_id = end($arr);
Thanks for the help, I've found a solution for the problem. I'm going to post an uncommented version of the code on pastebin, becuase I couldn't get the code saple thing working here.
code

PHP: preg_replace() to get "parent" component of NameSpace

How can I use the preg_replace() replace function to only return the parent "component" of a PHP NameSpace?
Basically:
Input: \Base\Ent\User; Desired Output: Ent
I've been doing this using substr() but I want to convert it to regex.
Note: Can this be done without preg_match_all()?
Right now, I also have a code to get all parent components:
$s = '\\Base\\Ent\\User';
print preg_replace('~\\\\[^\\\\]*$~', '', $s);
//=> \Base\Ent
But I only want to return Ent.
Thank you!
As Rocket Hazmat says, explode is almost certainly going to be better here than a regex. I would be surprised if it's actually slower than a regex.
But, since you asked, here's a regex solution:
$path = '\Base\Ent\User';
$search = preg_match('~([^\\\\]+)\\\\[^\\\\]+$~', $path, $matches);
if($search) {
$parent = $matches[1];
}
else {
$parent = ''; // handles the case where the path is just, e.g., "User"
}
echo $parent; // echos Ent
I think maybe preg_match might be a better choice for this.
$s = '\\Base\\Ent\\User';
$m = [];
print preg_match('/([^\\\\]*)\\\\[^\\\\]*$/', $s, $m);
print $m[1];
If you read the regular expression backwards, from the $, it says to match many things that aren't backslashes, then a backslash, then many things that aren't backslashes, and save that match for later (in $m).
How about
$path = '\Base\Ent\User';
$section = substr(strrchr(substr(strrchr($path, "\\"), 1), "\\"), 1);
Or
$path = '\Base\Ent\User';
$section = strstr(substr($path, strpos($path, "\\", 1)), "\\", true);

Remove string starting with something

How can I do the following with php?
This is my example:
http://www.example.com/index.php?&xx=okok&yy=no&bb=525252
I want remove this part: &yy=no&bb=525252
I just want this result:
http://www.example.com/index.php?&xx=okok
I tried this :
$str = 'bla_string_bla_bla_bla';
echo preg_replace('/bla_/', '', $str, 1); ;
but this not what I want.
Going for preg_replace was a good start. But you need to learn about regexes.
This will work:
$str = 'http://www.example.com/index.php?&xx=okok&yy=no&bb=525252';
echo preg_replace ('/&yy.+$/', '', $str);
Here the regex is &yy.+$
Let's see how this works:
&yy matches &yy obviously
.+ matches everything ...
$ ... until the end of the string.
So here, my replacement says : Replace whatever begins by &yy until the end of the string by nothing, which is actually simply deleting this part.
You can do this:
$a = 'http://www.example.com/index.php?&xx=okok&yy=no&bb=525252';
$b = substr($a,0,strpos($a,'&yy')); // Set in '&yy' the string to identify the beginning of the string to remove
echo $b; // Will print http://www.example.com/index.php?&xx=okok
Are you always expecting the end part to have the 'yy' variable name? You could try this:
$str = 'http://www.example.com/index.php?&xx=okok&yy=no&bb=525252';
$ex = explode('&yy=', $str, 2);
$firstPart = $ex[0];

How to convert a string with numbers and spaces into an int

I have a small problem. I am tryng to convert a string like "1 234" to a number:1234
I cant't get there. The string is scraped fro a website. It is possible not to be a space there? Because I've tried methods like str_replace and preg_split for space and nothing. Also (int)$abc takes only the first digit(1).
If anyone has an ideea, I'd be greatefull! Thank you!
This is how I would handle it...
<?php
$string = "Here! is some text, and numbers 12 345, and symbols !£$%^&";
$new_string = preg_replace("/[^0-9]/", "", $string);
echo $new_string // Returns 12345
?>
intval(preg_replace('/[^0-9]/', '', $input))
Scraping websites always requires specific code, you know how you receive the input - and you write code that is required to make it usable.
That is why first answer is still str_replace.
$iInt = (int)str_replace(array(" ", ".", ","), "", $iInt);
$str = "1 234";
$int = intval(str_replace(' ', '', $str)); //1234
I've just came into the same issue, however the answer that was provided wasn't covering all the different cases I had...
So I made this function (the idea popped in my mind thanks to Dan) :
function customCastStringToNumber($stringContainingNumbers, $decimalSeparator = ".", $thousandsSeparator = " "){
$numericValues = $matches = $result = array();
$regExp = null;
$decimalSeparator = preg_quote($decimalSeparator);
$regExp = "/[^0-9$decimalSeparator]/";
preg_match_all("/[0-9]([0-9$thousandsSeparator]*)[0-9]($decimalSeparator)?([0-9]*)/", $stringContainingNumbers, $matches);
if(!empty($matches))
$matches = $matches[0];
foreach($matches as $match):
$numericValues[] = (float)str_replace(",", ".", preg_replace($regExp, "", $match));
endforeach;
$result = $numericValues;
if(count($numericValues) === 1)
$result = $numericValues[0];
return $result;
}
So, basically, this function extracts all the numbers contained inside of a string, no matter how many text there is, identifies the decimal separator and returns every extracted number as a float.
One can specify what decimal separator is used in one's country with the $decimalSeparator parameter.
Use this code for removing any other characters like .,:"'\/, !##$%^&*(), a-z, A-Z :
$string = "This string involves numbers like 12 3435 and 12.356 and other symbols like !## then the output will be just an integer number!";
$output = intval(preg_replace('/[^0-9]/', '', $string));
var_dump($output);

Remove last character in a path string if it is a slash

I'm doing some url rewriting in PHP and need to find URLS with a slash at the end and then do a 301 redirect. I thought there'd be a simple PHP function to find last string, but I couldn't find anything. First instincts make m think I need to use regex, but I'm not 100%.
Here's one example:
http://domainx.com/characters/ I want to find a trailing slash and turn it into http://domainx.com/characters
So what function will help me check if the last character is a "/"?
A nice solution to remove safely the last / is to use
$string = rtrim($string, '/');
rtrim() removes all /s on the right side of the string when there is one or more.
You can also safely add exactly one single / at the end of an URL:
$string = rtrim($string, '/').'/';
You can use substr:
substr($str, -1)
This returns the last byte/character in a single-byte string. See also the multi-byte string variant mb_substr.
But if you just want to remove any trailing slashes, rtrim is probably the best solution.
And since you’re working with URLs, you might also take a look at parse_url to parse URLs as a trailing slash does not need to be part of the URL path.
$string[strlen($string)-1] gives you the last character.
But if you want to strip trailing slashes, you can do $string = rtrim($string, '/');. If there is no trailing slash, $string will remain unchanged.
You can use basename()
This will return characters for http://domainx.com/characters/ as well as http://domainx.com/characters
You can do like this:-
$page = $_SERVER['REQUEST_URI'];
$module = basename($page);
Then you can use the $module directly in your conditional logic without doing any redirects.
If you want to collect the last / trimmed URL then you can do this:-
If you are storing the project base url in a config file:-
BASE_URL = 'http://example.com'
then you can do this:-
$page = $_SERVER['REQUEST_URI'];
$module = basename($page);
$trimmedUrl = BASE_URL.'/'.$module;
You could preg_replace() a / at the end of the subject
$url = 'http://domainx.com/characters/';
$url = preg_replace('/(?:\/)$/', '', $url);
If you have php > 7.1
$string[-1]
Will give you the last character
http://sandbox.onlinephpfunctions.com/code/ff439889f14906749e4eb6328796c354c60f269b
Difference between rtrim and custom function:
<?php
$string0 = 'hi//';
$string1 = 'hello/';
$string2 = 'world';
function untrailingslashit( $string ) {
return $string[-1] === '/' ? substr( $string, 0, -1) : $string;
}
echo untrailingslashit($string0);
echo "\n";
echo untrailingslashit($string1);
echo "\n";
echo untrailingslashit($string2);
echo "\n";
echo rtrim($string0, "/");
Result:
hi/
hello
world
hi
With PHP 8
str_ends_with($string, '/');
New str_starts_with() and str_ends_with() functions are added into the core.
This is coming straight from WordPress:
function untrailingslashit( $string ) {
return rtrim( $string, '/\\' );
}

Categories