I use $_SERVER['REQUEST_URI'] to get this /res/about_us.php, I want the output to be About Us, I know I can use preg_replace for this, it is the regular expression I am struggling with.
I have this pitiful attempt thus far:
echo str_replace('.php', '', $uri);
I realised after this that I cant replace two cases using str_replace... So I thought I need preg_replace with regex, but not a clue how it works, cant seem to find a similar example through Google.
Regards
Without regular expressions you can do:
// Get the filename, e.g., 'about_us'.
$filename = pathinfo($_SERVER['REQUEST_URI'], PATHINFO_FILENAME);
// Replace underscore with spaces and capitalise words
$title = ucwords(str_replace('_', ' ', $filename));
See pathinfo, ucwords
Actually you can replace multiple cases with str_replace by passing an array of things you'd like to replace as first parameter of the function! Something like this:
echo ucwords(str_replace(array('_', '-', '.php'), ' ', basename($uri)));
Inside the array you could put whatever you'd like to replace.
Related
I have a text file containing this; "I do not know" character. Already search on google but I'm having hard time getting desired search result since I do not know what is the general term for this kind of character.
I tried removing it using below code but nothing happens. I also tried "\f" because I thought that character is form feed but still can't remove.
$replace = str_replace("\0", ' ', $str);
EDIT:
The said character is really form feed but somehow below code is not working for me.
$replace = str_replace("\f", ' ', $str);
You can use prep_replace command to perform a regular expression search and replace.
$replace = preg_replace( '/[^A-Za-z0-9 _\-\+\&]/', '',$str);
Note: You need to decide the first parameter to the preg_replace function call for the set of unwanted characters you don't want. You might be interested to remove non printable characters.
I do not know why, but using str_replace is not working to remove the 'FF' (Form Feed) character
$replace = str_replace("\f", ' ', $str); // not working
Using below code solves my problem but kinda not look good because it is using regex to replace a single character only. Still, this works:
$replace = preg_replace('/[\f]/', " ", $str);
Seems like an issue with your header. Try once after adding this on you header.
header('Content-Type: text/html; charset=UTF-8');
Hope this helps
I try to delete /en. It works well:
$url = "myDomain/en/firstFolder/secondFolder/file.php";
echo str_replace("/en","",$url);
My problem comes when it could be: /en or /fr. I mean $url could be:
"myDomain/en/firstFolder/secondFolder/file.php";
"myDomain/fr/firstFolder/secondFolder/file.php";
I cannot know if I have /en or /fr. How to delete in both cases?
I tried and of course, it does not work:
echo str_replace("/en|/fr","",$url);
str_replace() is able to accept an array as the first two arguments, for example (from the Docs):
search The value being searched for, otherwise known as the needle.
An array may be used to designate multiple needles.
You can use:
echo str_replace( array('/en', '/fr'), '', $url );
Fiddle Demo
str_replace is used to replace string, If you want to use pattern then use preg_replace
$url = "myDomain/fr/firstFolder/secondFolder/file.php";
echo preg_replace('/\/en|\/fr/','',$url);
If you can't be bothered with making an array of the replacements, use a regular expression:
echo preg_replace('#/(en|fr|es|ru|mm)#', '', $url);
...and you might want to do the following to make sure you don't accidentally trim too much:
echo preg_replace('#/(en|fr|es|ru|mm|fi)/#', '/', $url);
Say your language was Finnish ('/fi') -- you would also effectively get rid of the beginning of '/firstFolder', unless you matched /fi/ with leading and trailing slashes, and substituted it with a single slash. If you can't be bothered enumerating all the languages, you can also simply...
echo preg_replace('#myDomain/[a-z]{2}/#', 'myDomain/', $url);
...which seems like the safest and most elegant way to get there.
Instead of wondering what regex I need for each time I need a regex, I like to learn how to do basic string replacement with regexes.
How do you take one string and replace it with another with regexes in PHP ?
For example how do you take all '/' and replace them with '%' ?
If you just want to do basic string replacement (i.e. replace all 'abc' with '123') then you can use str_replace, which doesn't require using regex. For basic replacements, this will be easier to set up and should run faster.
If you want to use this as a tool to learn regex though (or need more complicated replacements) then preg_replace is the function you need.
You should look into preg_replace. For your question
$string = "some/with/lots/of/slashes";
$new_string = preg_replace("/\//","%",$string);
echo $new_string;
I like to learn how to do basic string replacement with regexes.
That's a little broad for this forum. However, to answer a more specific question like:
For example how do you take all '/' and replace them with '%' ?
You could do that like this:
$result = preg_replace('#\/#', '%', 'Here/is/a/test/string.');
Here is a Rubular that proves the regex.
Note, you are not limited to using the common / delimiter, which means when working with forward slashes it is often easier to change to a different delimiter EG.
$mystring = 'this/is/random';
$result = preg_replace('#/#', '%', $mystring);
This will make '#' the delimiter, rather than the standard '/', so it means you do not need to escape the slash.
I would do this simply with strtr which is very suitable for character mapping, e.g.
strtr('My string has / slashes /', '/', '%');
If you want to also replace the letter a with a dash:
strtr('My string has / slashes /', '/a', '%-');
As you can see, the second and third argument define the transformation map.
I currently have this regex:
$text = preg_replace("#<sup>(?:(?!</?sup).)*$key(?:(?!</?sup).)*<\/sup>#is", '<sup>'.$val.'</sup>', $text);
The objective of the regex is to take <sup>[stuff here]$key[stuff here]</sup> and remove the stuff within the [stuff here] locations.
What I actually would like to do, is not remove $key[stuff here]</sup>, but simply move the stuff to $key</sup>[stuff here]
I've tried using $1-$4 and \\1-\\4 and I can't seem to get the text to be added after </sup>
Try this;
$text = preg_replace(
'#<sup>((?:(?!</?sup).)*)'.$key.'((?:(?!</?sup).)*)</sup>#is',
'<sup>'.$val.'</sup>\1\2',
$text
);
The (?:...)* bit isn't actually a sub-pattern, and is therefor not available using backreferences. Also, if you use ' rather than " for string literals, you will only need to escape \ and '
// Cheers, Morten
You have to combine preg_match(); and preg_replace();
You match the desired stuff with preg_match() and store in to the variable.
You replace with the same regex to empty string.
Append the variable you store to at the end.
I'm trying to strip part of a string (which happens to be a url) with Regex. I'm getting better out regex but can't figure out how to tell it that content before or after the string is optional. Here is what I have
$string='http://www.example.com/username?refid=22';
$new_string= preg_replace('/[/?refid=0-9]+/', '', $string);
echo $new_string;
I'm trying to remove the ?refid=22 part to get http://www.example.com/username
Ideas?
EDIT
I think I need to use Regex instead of explode becuase sometimes the url looks like http://example.com/profile.php?id=9999&refid=22 In this case I also want to remove the refid but not get id=9999
parse_url() is good for parsing URLs :)
$string = 'http://www.example.com/username?refid=22';
$url = parse_url($string);
// Ditch the query.
unset($url['query']);
echo array_shift($url) . '://' . implode($url);
CodePad.
Output
http://www.example.com/username
If you only wanted to remove that specific GET param, do this...
parse_str($url['query'], $get);
unset($get['refid']);
$url['query'] = http_build_query($get);
CodePad.
Output
http://example.com/profile.php?id=9999
If you have the extension, you can rebuild the URL with http_build_url().
Otherwise you can make assumptions about username/password/port and build it yourself.
Update
Just for fun, here is the correction for your regular expression.
preg_replace('/\?refid=\d+\z/', '', $string);
[] is a character class. You were trying to put a specific order of characters in there.
\ is the escape character, not /.
\d is a short version of the character class [0-9].
I put the last character anchor (\z) there because it appears it will always be at the end of your string. If not, remove it.
Dont use regexs if you dont have to
echo current( explode( '?', $string ) );