Replace a specified portion of a string - php

How can I use str_replace method for replacing a specified portion(between two substrings).
For example,
string1="www.example.com?test=abc&var=55";
string2="www.example.com?test=xyz&var=55";
I want to replace the string between '?------&' in the url with ?res=pqrs&. Are there any other methods available?

You could use preg_replace to do that, but is that really what you are trying to do here?
$str = preg_replace('/\?.*?&/', '?', $input);
If the question is really "I want to remove the test parameter from the query string" then a more robust alternative would be to use some string manipulation, parse_url or parse_str and http_build_query instead:
list($path, $query) = explode('?', $input, 2);
parse_str($query, $parameters);
unset($parameters['test']);
$str = $path.'?'.http_build_query($parameters);

Since you're working with URL's, you can decompose the URL first, remove what you need and put it back together like so:
$string1="www.example.com?test=abc&var=55";
// fetch the part after ?
$qs = parse_url($string1, PHP_URL_QUERY);
// turn it into an associative array
parse_str($qs, $a);
unset($a['test']); // remove test=abc
$a['res'] = 'pqrs'; // add res=pqrs
// put it back together
echo substr($string1, 0, -strlen($qs)) . http_build_query($a);
There's probably a few gotchas here and there; you may want to cater for edge cases, etc. but this works on the given inputs.

Dirty version:
$start = strpos($string1, '?');
$end = strpos($string1, '&');
echo substr($string1, 0, $start+1) . '--replace--' . substr($string1, $end);
Better:
preg_replace('/\?[^&]+&/', '?--replace--&', $string1);
Depending on whether you want to keep the ? and &, the regex can be mofidied, but it would be quicker to repeat them in the replaced string.

Think of regex
<?php
$string = 'www.example.com?test=abc&var=55';
$pattern = '/(.*)\?.*&(.*)/i';
$replacement = '$1$2';
$replaced = preg_replace($pattern, $replacement, $string);
?>

Related

How to remove the first two directories from a file path string?

I have a string "./product_image/Bollywood/1476813695.jpg".
first I remove . from first.
now I want to remove all character between first two / . that means I want
Bollywood/1476813695.jpg
I am trying with this but not work
substr(strstr(ltrim('./product_image/Bollywood/1476813695.jpg', '.'),"/product_image/"), 1);
It always return product_image/Bollywood/1476813695.jpg
Easily done with explode():
$orig = './product_image/Bollywood/1476813695.jpg';
$origArray = explode('/', $orig);
$new = $origArray[2] . '/' . $origArray[3];
result:
Bollywood/1476813695.jpg
If you want something a little different you can use regex with preg_replace()
$pattern = '/\.\/(.*?)\//';
$string = './product_image/Bollywood/1476813695.jpg';
$new = preg_replace($pattern, '', $string);
This returns the same thing and you could, if you wanted, put it all in one line.
$str = "./product_image/Bollywood/1476813695.jpg";
$str_array = explode('/', $str);
$size = count($str_array);
$new_string = $str_array[$size - 2] . '/' . $str_array[$size - 1];
echo $new_string;
please follow the below code
$newstring = "./product_image/Bollywood/1476813695.jpg";
$pos =substr($newstring, strpos($newstring, '/', 2)+1);
var_dump($pos);
and output will be looking
Bollywood/1476813695.jpg
for strpos function detail please go to below link
http://php.net/manual/en/function.strpos.php
for substr position detail please go to below link
http://php.net/manual/en/function.substr.php

PHP - Delete part of a string

I'm new to PHP and I have a problem.
I need delete all chars since a symbol (Sorry for my bad english , i'm from argentina)
I have this text :
3,94€
And I need the text is as follows:
3,94
I tried this by multiple ways but it didn't work.
There are a few ways you can do this:
Using strpos:
$string = '3,94€';
echo substr($string, 0, strpos($string, '&'));
or using strstr:
// Requires PHP 5.3+ due to the true (before_needle) parameter
$string = '3,94€';
echo strstr($string, '&', true);
or using explode:
// Useful if you need to keep the &#8364 part for later
$string = '3,94€';
list($part_a, $part_b) = explode('&', $string);
echo $part_a;
or using reset:
$string = '3,94€';
echo reset(explode('&', $string));
The best suited in your case would be to use strpos to find the first occurrence of & in the string, and then use substr to return the string from the begining until the value returned by strpos.
Another posibility is clean the number and then round it:
<?php
//Option 1: with regular expresions:
$val = '3,94&#8364';
$res = preg_replace('/[^0-9.,]/','',$val);
var_dump($res);
//Option 2: with filter functions:
$res2 = filter_var($val, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);
var_dump($res2);
//Output: 3,948364
//If you want to round it:
$res = substr($res, 0, 4);
var_dump($res);
?>
You can use regex: https://regex101.com/r/uY0kH3/1
It will work in preg_match() function.
You could use str_replace.
<?php
$string = 3,94€
$final = str_replace('&#8364' ,'', $string);
echo $final;

isolate the number exists at the end of the URI php

I have the following URI:
/belt/belts/fk/product/40P35871
And I want to retrieve the last content after the last /.
In this case is 40P35871.
How can I do this?
How about explode?
$elements = explode('/', $input);
$productId = end($elements);
Here's a different solution entirely. (and the simplest!)
Using basename
$var = "/belt/belts/fk/product/40P35871";
echo basename($var);
Output:
40P35871
You don't need regex for something simple like that. Consider using strrchr, documentation here
$lastcontent = substr(strrchr($uri, "/"), 1);
Considering this special case of $uri being a path, the best answer would be the one provided by Chtulhu.
basename will return the last part of a path, documentation here
$lastcontent = basename($uri);
Just like this
$str = '/belt/belts/fk/product/40P35871';
$arr = explode('/', $str);
$var = array_pop($arr);
var_dump($var);
or
$var = substr($str, strrpos($str,'/') + 1);
Try this
$result = preg_replace('%(/(?:[^/]+?/)+)([^/]+)\b%', '$2', $subject);
use this:
echo preg_replace('/[a-z0-9]$/i', '$1', $url);
this will give you the last position
note: but on this url only, query strings make this useless and use need to parse the url for the same first for this to work
Don't use regex. In this case you can act as the follow
myUrl = $_SERVER[REQUEST_URL];
$number = substr(strrpos(myUri,'/')+1);
You don't need regex.
Find the last content and get it using substr():
$lastcontent = substr(strrchr($uri, "/"), 1);

Removing last part of string divided by a colon

I have a string that looks a little like this, world:region:bash
It divides folder names, so i can create a path for FTP functions.
However, i need at some points to be able to remove the last part of the string, so, for example
I have this world:region:bash
I need to get this world:region
The script wont be able to know what the folder names are, so some how it needs to be able to remove the string after the last colon.
$res=substr($input,0,strrpos($input,':'));
I should probably highlight that strrpos not strpos finds last occurrence of a substring in given string
$tokens = explode(':', $string); // split string on :
array_pop($tokens); // get rid of last element
$newString = implode(':', $tokens); // wrap back
You may want to try something like this:
<?php
$variable = "world:region:bash";
$colpos = strrpos($variable, ":");
$result = substr($variable, 0, $colpos);
echo $result;
?>
Or... if you create a function using this information, you get this:
<?php
function StrRemoveLastPart($string, $delimiter)
{
$lastdelpos = strrpos($string, $delimiter);
$result = substr($string, 0, $lastdelpos);
return $result;
}
$variable = "world:region:bash";
$result = StrRemoveLastPart($variable, ":");
?>
Explode the string, and remove the last element.
If you need the string again, use implode.
$items = array_pop(explode(':', $the_path));
$shotpath = implode(':', $items);
Use regular expression /:[^:]+$/, preg_replace
$s = "world:region:bash";
$p = "/:[^:]+$/";
$r = '';
echo preg_replace($p, $r, $s);
demo
Notice how $ which means string termination, is made use of.
<?php
$string = 'world:region:bash';
$string = implode(':', explode(':', $string, -1));

PHP - Strip a specific string out of a string

I've got this string, but I need to remove specific things out of it...
Original String: hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64.
The string I need: sh-290-92.ch-215-84.lg-280-64.
I need to remove hr-165-34. and hd-180-1.
!
EDIT: Ahh ive hit a snag!
the string always changes, so the bits i need to remove like "hr-165-34." always change, it will always be "hr-SOMETHING-SOMETHING."
So the methods im using wont work!
Thanks
Depends on why you want to remove exactly those Substrigs...
If you always want to remove exactly those substrings, you can use str_replace
If you always want to remove the characters at the same position, you can use substr
If you always want to remove substrings between two dots, that match certain criteria, you can use preg_replace
$str = 'hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64';
$new_str = str_replace(array('hr-165-34.', 'hd-180-1.'), '', $str);
Info on str_replace.
The easiest and quickest way of doing this is to use str_replace
$ostr = "hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64";
$nstr = str_replace("hr-165-34.","",$ostr);
$nstr = str_replace("hd-180-1.","",$nstr);
<?php
$string = 'hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64';
// define all strings to delete is easier by using an array
$delete_substrings = array('hr-165-34.', 'hd-180-1.');
$string = str_replace($delete_substrings, '', $string);
assert('$string == "sh-290-92.ch-215-84.lg-280-64" /* Expected result: string = "sh-290-92.ch-215-84.lg-280-64" */');
?>
Ive figured it out!
$figure = $q['figure']; // hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64
$s = $figure;
$matches = array();
$t = preg_match('/hr(.*?)\./s', $s, $matches);
$s = $figure;
$matches2 = array();
$t = preg_match('/hd(.*?)\./s', $s, $matches2);
$s = $figure;
$matches3 = array();
$t = preg_match('/ea(.*?)\./s', $s, $matches3);
$str = $figure;
$new_str = str_replace(array($matches[0], $matches2[0], $matches3[0]), '', $str);
echo($new_str);
Thanks guys!

Categories