I have a string http://localhost:9000/category that I want to replace with category.html, i.e. strip everything before /category and add .html.
But can't find a way to do this with str_replace.
You want to use parse_url in this case:
$parts = parse_url($url);
$file = $parts['path'].'.html';
Or something along that line. Experiment a bit with it.
Ismael Miguel suggested this shorter version, and I like it:
$file = parse_url($url,PHP_URL_PATH).'.html';
Much better than a ^*!$(\*)+ regular expression.
.*\/(\S+)
Try this.Replace by $1.html.see demo .
http://regex101.com/r/nA6hN9/43
Use preg_replace instead of str_replace
Regex:
.*\/(.+)
Replacement string:
$1.html
DEMO
$input = "http://localhost:9000/category";
echo preg_replace("~.*/(.+)~", '$1.html', $input)
Output:
category.html
A solution without regex:
<?php
$url = 'http://localhost:9000/category';
echo #end(explode('/',$url)).'.html';
?>
This splits the string and gets the last part, and appends .html.
Note that this won't work if the input ends with / (e.g.: $url = 'http://localhost:9000/category/';)
Also note that this relies on non-standard behavior and can be easily changed, this was just made as a one-liner. You can make $parts=explode([...]); echo end($parts).'.html'; instead.
If the input ends with / occasionally, we can do like this, to avoid problems:
<?php
$url = 'http://localhost:9000/category/';
echo #end(explode('/',rtrim($url,'/'))).'.html';
?>
Related
I have a path "../uploads/e2c_name_icon/" and I need to extract e2c_name_icon from the path.
What I tried is using str_replace function
$msg = str_replace("../uploads/","","../uploads/e2c_name_icon/");
This result in an output "e2c_name_icon/"
$msg=str_replace("/","","e2c_name_icon/")
There is a better way to do this. I am searching alternative method to use regex expression.
Try this. Outputs: e2c_name_icon
<?php
$path = "../uploads/e2c_name_icon/";
// Outputs: 'e2c_name_icon'
echo explode('/', $path)[2];
However, this is technically the third component of the path, the ../ being the first. If you always need to get the third index, then this should work. Otherwise, you'll need to resolve the relative path first.
Use basename function provided by PHP.
$var = "../uploads/e2c_name_icon/";
echo basename( $var ); // prints e2c_name_icon
If you are strictly want to get the last part of the url after '../uploads'
Then you could use this :
$url = '../uploads/e2c_name_icon/';
$regex = '/\.\.\/uploads\/(\w+)/';
preg_match($regex, $url, $m)
print_r ($m); // $m[1] would output your url if possible
You can trim after the str_replace.
echo $msg = trim(str_replace("../uploads/","","../uploads/e2c_name_icon/"), "/");
I don't think you need to use regex for this. Simple string functions are usually faster
You could also use strrpos to find the second last /, then trim off both /.
$path = "../uploads/e2c_name_icon/";
echo $msg = trim(substr($path, strrpos($path, "/",-2)),"/");
I added -2 in strrpos to skip the last /. That means it returns the positon of the / after uploads.
So substr will return /e2c_name_icon/ and trim will remove both /.
You'd be much better off using the native PHP path functions vs trying to parse it yourself.
For example:
$path = "../uploads/e2c_name_icon/";
$msg = basename(dirname(realpath($path))); // e2c_name_icon
I am trying to change all the links of a html with php preg_replace. All the uris have the following form
test.com/item/16
I want to change it to:
test.com/z/item/16
I tried the following, but it returns no changes:
$links = 'http://test.com/item/16';
preg_replace("/item","z/item",$links);
echo $links;
// output >>> http://test.com/z/item/16
You have to use delimiters as #nickb has pointed out, i.e. /your_regular_expression/. The / is the standard delimiter for regular expressions, and so, it being a special character, you'd have to escape the / you want to match by using a backslash, \/:
preg_replace("/\/item/","z/item",$links);
But luckily, you can choose your own delimiters, like #, so then no need to escape the /:
preg_replace("#/item#","z/item",$links);
Do this:
<?php
$links = 'http://test.com/item/16';
$a = preg_replace("/item/","z/item",$links);
echo $a;
preg_replace does not change the input string but instead returns a modified string....which is stored in $a variable..
You need delimiter and return of preg_replace set to variable
$links = 'http://test.com/item/16';
$links = preg_replace('/\/item/','/z/item',$links);
echo $links;
But, why don't you use just str_replace in this case?
The problem with the provided answers is that if you have more than one instance of /item in the URL, all of them will get replaced, for example a URL like:
http://items.domain.com/item/16
would get messed up, try modifying just the path:
$path = parse_url( $url, PHP_URL_PATH );
$url = str_replace( $path, '/z'.$path, $url );
I have strings like this
[Ljava.lang.String;
[Ldummy.class.Here;
[Lanother.unknown.Class;
What regex should i use to replace [L and ; with <span>,[]</span>
And make it look like this
<span>java.lang.String[]</span>
<span>dummy.class.Here[]</span>
<span>another.unknown.Class[]</span>
What i want is to make java array class string representation more human friendly
I've heard about $1 or something like that, but i couldn't find more information as i don't know what is it
$strings = "[Ljava.lang.String;
[Ldummy.class.Here;
[Lanother.unknown.Class;";
$strings = preg_replace('/\[L([A-Za-z\.]+);/', '<span>$1[]</span>', $strings);
echo $strings;
Output:
$ php foo.php
<span>java.lang.String[]</span>
<span>dummy.class.Here[]</span>
<span>another.unknown.Class[]</span>
If you want to use plain old PHP for this rather than a regex, here is a simple snippet that will do exactly what you need - and you can modify it without having to sort through regex that makes little sense to you:
<?php
$stringArray=array(
'[Ljava.lang.String;',
'[Ldummy.class.Here;',
'[Lanother.unknown.Class;'
);
foreach($stringArray as $val)
{
$output=$val;
if($val[0].$val[1]=='[L')
{
$output="<span>".substr($val,2);
}
if(substr($output,-1)==';')
{
$output=substr($output,0,strlen($output)-1).'</span>';
}
echo $output.'<br>';
}
?>
Output:
<span>java.lang.String</span>
<span>dummy.class.Here</span>
<span>another.unknown.Class</span>
This should do it:
$new_content = preg_replace('#^\[L(.*);\s*$#m', '<span>$1[]</span>', $content);
Demo here: http://sandbox.onlinephpfunctions.com/code/8f0de08b5ba0882db2d98d99cdd961b9aebab074
You can use this:
$result = preg_replace('~\[L([^;]+);~', '<span>$1[]</span>', $txt);
where [^;]+ matches all that is not a ";"
A column in my spreadsheet contains data like this:
5020203010101/FIS/CASH FUND/SBG091241212
I need to extract the last part of string after forwward slash (/) i.e; SBG091241212
I tried the following regular expression but it does not seem to work:
\/.*$
Any Idea?
Try this:
'/(?<=\/)[^\/]*$/'
The reason your current REGEXP is failing is because your .* directive matches slashes too, so it anchors to the first slash and gives you everything after it (FIS/CASH FUND/SBG091241212).
You need to specify a matching group using brackets in order to extract content.
preg_match("/\/([^\/]+)$/", "5020203010101/FIS/CASH FUND/SBG091241212", $matches);
echo $matches[1];
You could do it like this without reg ex:
<?php
echo end(explode('/', '5020203010101/FIS/CASH FUND/SBG091241212'));
?>
this will do a positive lookbehind and match upto a value which does not contain a slash
like this
[^\/]*?(?<=[^\/])$
this will only highlight the match . i.e. the last part of the url
demo here : http://regex101.com/r/pF8pS2
Make use of substr() with strrpos() as a look behind.
echo substr($str,strrpos($str,'/')+1); //"prints" SBG091241212
Demo
You can 'explode' the string:
$temp = explode('/',$input);
if (!empty($temp)){
$myString = $temp[count($temp)-1];
}
You can also use:
$string = '5020203010101/FIS/CASH FUND/SBG091241212';
echo basename($string);
http://www.php.net/manual/en/function.basename.php
I have the following in a variable, |MyString|
I want to strip the leading | and the ending | returning MyString
What is the quickest and non intensive way of doing this?
Easiest way is probably
$result = trim($input, '|');
http://docs.php.net/trim
e.g.
<?php
$in = '|MyString|';
$result = trim($in, '|');
echo $result;
prints MyString
Checkout the str_replace function in PHP http://php.net/manual/en/function.str-replace.php
this should remove all '|' characters:
str_replace('|','',$myString)
You may be able to use a regular expression to only remove the first and last '|' or alternatively using the String trim() function may also work:
http://www.php.net/manual/en/function.trim.php
So, something like this:
$trimmedMyString = trim($myString, "|");
Worth trying anyway.