Php regex to get results of 4 strings between slashes - php

I'm having troubles with regex. I'm trying to isolate query results that are like :
string1/string2/string3/string4
string1/string2/string3/string4/string5
I want to find the first case from the two above, the one with the chain ending after "string4".
I've tryied this regex that doesn't actually works :
$my_regex = "/^(.+)\/(.+)\/(.+)\/(.+)$/";
if (preg_match($my_regex, $category->name)) {
...
}
Am I missing something ?

With a regex, a solution could be :
$my_regex = "/^([^\/]+\/){3}[^\/]+$/";
if (preg_match($my_regex, $category->name)) {
...
}

Don't use a regex, use explode() function
$pieces = explode("/", $your_string); //pieces will be an array
foreach($pieces as $piece) {
[...]
}

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

How to get last part of a string?

I have this string:
"application/controllers/backend"
I want get:
backend
of course the backend it's dynamic, so could be change, so I'm looking for a solution that allow me to get only the last part of the string. How I can do that?
You can take the advantage of basename() to get the last part
in your case, it will be
basename("application/controllers/backend");
Output:
backend
Some thing like this :
echo end(explode("/", $url));
If this thorws error then do :
$parts = explode("/", $url);
echo end($parts);
$arr = explode ("/", $string);
//$arr[2] is your third element in the string
http://php.net/manual/en/function.explode.php
Just use
basename("application/controllers/backend");
http://php.net/manual/en/function.basename.php
And, if you want to do it with a regex:
$result = (preg_match('%.*[/\\\\](.*?)$%', $url, $regs)) ? $regs[1] : '';
You did ask initially for a solution with regex, so, although the other answers haven't involved regex, here is one approach which does.
You can use preg_match and str_replace for this:
$string = '"application/controllers/backend"';
preg_match('/[^\/]+"/', $string, $matches);
$last_item = str_replace('"','',$matches[0]);
$last_item is now a string containing the word backend.

Content Spinning using PHP?

Can anyone please help me? Say if I had this text or a smaller section stored in a variable, how can I randomise the words in the '{ }' ?
For example, the first one is "{important|essential|crucial|critical|vital|significant}" how can I make PHP choose one of those words randomly and then echo it? Thanks for helping me. :)
http://webarto.com/62/random-sentence-spinning-function
function get_random($matches)
{
$rand = array_rand($split = explode("|", $matches[1]));
return $split[$rand];
}
function show_randomized($str)
{
$new_str = preg_replace_callback('/\{([^{}]*)\}/im', "get_random", $str);
if ($new_str !== $str) $str = show_randomized($new_str);
return $str;
}
Applied on your text file... http://ideone.com/rkuf6
strip off initial and ending curly braces, you can use trim()
explode the resulting string on | using explode()
use array_rand() for the array you had in last step
Will not work with nested({a|x {b|c} y|z})!
function doStuff($from){
$to="";
while(($pos=strpos($from,'{'))!==false){
$to.=substr($from,0,$pos);
$from=substr($from,$pos);
$closepos=strpos($from,'}');
$arr=explode('|',substr($from,1,$closepos-1));
$to.=$arr[array_rand($arr)];
$from=substr($from,$closepos+1);
}
return $to.$from;
}

php how to make a if str_replace?

$str is some value in a foreach.
$str = str_replace('_name_','_title_',$str);
how to make a if str_replace?
I want do the thing if have a str_replace then echo $str, else not, jump the current foreach then to the next. Thanks.
There is a fourth parameter to str_replace() that is set to the number of replacements performed. If nothing was replaced, it's set to 0. Drop a reference variable there, and then check it in your if statement:
foreach ($str_array as $str) {
$str = str_replace('_name_', '_title_', $str, $count);
if ($count > 0) {
echo $str;
}
}
If you need to test whether a string is found within another string, you can like this.
<?php
if(strpos('_name_', $str) === false) {
//String '_name_' is not found
//Do nothing, or you could change this to do something
} else {
//String '_name_' found
//Replacing it with string '_title_'
$str = str_replace('_name_','_title_',$str);
}
?>
http://php.net/manual/en/function.strpos.php
However you shouldn't need to, for this example. If you run str_replace on a string that has nothing to replace, it won't find anything to replace, and will just move on without making any replacements or changes.
Good luck.
I know this is an old question, but it gives me a guideline to solve my own checking problem, so my solution was:
$contn = "<p>String</p><p></p>";
$contn = str_replace("<p></p>","",$contn,$value);
if ($value==0) {
$contn = nl2br($contn);
}
Works perfectly for me.
Hope this is useful to someone else.

Searching within an array of strings

Ok, I'm feeling retarded here,
I have a string like so:
$string = 'function module_testing() {';
or it could be like this:
$string = 'function module_testing()';
or it could be like this:
$string = 'function module_testing($params) {';
or this:
$string = 'function module_testing($params, $another = array())';
and many more ways...
And than I have an array of strings like so:
$string_array = array('module_testing', 'another_function', 'and_another_function');
Now, is there some sort of preg_match that I can do to test if any of the $string_array values are found within the $string string at any given position? So in this situation, there would be a match. Or is there a better way to do this?
I can't use in_array since it's not an exact match, and I'd rather not do a foreach loop on it if I can help it, since it's already in a while loop.
Thanks :)
A foreach loop here is the appropriate solution. Not only is it the most readable but you're looping over three values. The fact that happens within a while loop is a non-issue.
foreach ($string_array as $v) {
if (strpos($string, $v) !== false) {
// found
}
}
You can alternatively use a regular expression:
$search = '\Q' . implode('\E|\Q', $string_array) . '\E';
if (preg_match('!$search!`, $string)) {
// found
}
There are two parts to this. Firstly, there is the | syntax:
a|b|c
which means find a, b or c. The second part is:
\Q...\E
which escapes the contents. This means if your search strings contain any regex special characters (eg () then the regex will still work correctly.
Ultimately though I can't see this being faster than the foreach loop.

Categories