Doing a substring operation based on a regex in PHP - php

In Python, I can do substring operations based on a regex like this.
rsDate = re.search(r"[0-9]{2}/[0-9]{2}/[0-9]{4}", testString)
filteredDate = rsDate.group()
filteredDate = re.sub(r"([0-9]{2})/([0-9]{2})/([0-9]{4})", r"\3\2\1", filteredDate)
What's the PHP equivalent to this?

You could simply use the groups to build your filteredDate :
$groups = array();
if (preg_match("([0-9]{2})/([0-9]{2})/([0-9]{4})", $testString, $groups))
$filteredDate = sprintf('%s%s%s', $groups[3], $groups[2], $groups[1]);
else
$filteredDate = 'N/A';

so you want a replace...
$filteredDate = preg_replace("([0-9]{2})/([0-9]{2})/([0-9]{4})","$3$2$1",$testString);

Try this:
$result = preg_replace('#([0-9]{2})/([0-9]{2})/([0-9]{4})#', '\3\2\1' , $data);

Related

What is the most efficient way to add content to a position on a string with php

I have a string localhost/uploads/images/photo.jpg, I just want to simply rename it to localhost/upload/images/photo_thumb.jpg, keeping in mind that is a dynamic data and am just using it to simply what I want to achieve. I have tried to use the strpos() function to get the position of the '.' then use it for something(this where I got lost), then another thought came to me use implode. I will appreciate if some can help me figure this out thanks.
<?php
function get_google_image_url($type, $id, $column = 'image', $multi = "",$thumb=''){
if($multi ==''){
//check if there is thumbnail add _thumb before extention
if($thumb != ''){
$l= $this->db->get_where($type,array($type.'_id'=>$id));
$n = $l->num_rows();
if($n >0){
$value = $l->row()->$column;
$position = strripos($value,'.');
return $l->row()->$column;
}
}else{
$l= $this->db->get_where($type,array($type.'_id'=>$id));
$n = $l->num_rows();
if($n >0){
/$value = $l->row()->$column
$position = strripos($value,'.');
//this where i got stucked
//return $l->row()->$column;
}
}
}
}
that's the function am trying to implement it in, but what I want to achieve is what I stated above.
i think the best way here is to use pathinfo
something like that should work
$path_parts = pathinfo('localhost/uploads/images/photo.jpg');
$strNewName = $path_parts['dirname'].'/photo_thumb.jpg';
echo $strNewName;
I would do it by using regex and preg_replace:
$string="localhost/uploads/images/photo_thumb.jpg";
$replacement="$1/$2_thumb.$3";
$pattern= '/([\w+\/]*)(?=\/)\/([\w]+(?<!_thumb))\.(\w+)/i';
echo preg_replace($pattern, $replacement, $string);
code you can run it here
$1 = matching until last /
$2 = name of the file
$3 = file extension
feel free to improve the regex pattern if needed.

Isolate substring at end of string after a specific substring

My query generates a result set of UID values which looks like:
855FM21
855FM22
etc
I want to isolate the last number from the UID which it can be done by splitting the string.
How to split this string after the substring "FM"?
To split this string after the sub string "FM", use explode with delimiter as FM. Do like
$uid = "855FM22";
$split = explode("FM",$uid);
var_dump($split[1]);
You can use the explode() method.
<?php
$UID = "855FM21";
$stringParts = explode("FM", $UID);
$firstPart = $stringParts[0]; // 855
$secondPart = $stringParts[1]; // 21
?>
use explode function it returns array. to get the last index use echo $array[count($array) - 1];
<?php
$str = "123FM23";
$array = explode("FM",$str);
echo $array[count($array) - 1];
?>
For it,please use the explode function of php.
$UID = "855FM21";
$splitToArray = explode("FM",$UID);
print_r($splitToArray[1]);
Have you tried the explode function of php?
http://php.net/manual/en/function.explode.php
As a matter of best practice, never ask for more from your mysql query than you actually intend to use. The act of splitting the uid can be done in the query itself -- and that's where I'd probably do it.
SELECT SUBSTRING_INDEX(uid, 'FM', -1) AS last_number FROM `your_tablename`
If you need to explode, then be practice would indicate that the third parameter of explode() should set to 2. This way, the function doesn't waste any extra effort looking for more occurrences of FM.
echo explode('FM', $uid, 2)[1]; // 21
If you want to use php to isolate the trailing number in the uid, but don't want explode() for some reason, here are some wackier / less efficient techniques:
$uid = '855FM21';
echo strtok($uid, 'FM') ? strtok('FM') : ''; // 21
echo preg_replace('~.*FM~', '', $uid); // 21
echo ltrim(ltrim($uid, '0..9'), 'MF'); // 21
$uid = '123FM456';
$ArrUid = split( $uid, 'FM' );
if( count( $ArrUid ) > 1 ){
//is_numeric check ?!
$lastNumbers = $ArrUid[1];
}
else{
//no more numbers after FM
}
You can also use regular expressions to extract the last numbers!
a simple example
$uid = '1234FM56';
preg_match( '/[0-9]+fm([0-9]+)/i', $uid, $arr );
print_r($arr); //the number is on index 1 in $arr -> $arr[1]

Remove parameter from link

I have many links with parameter number - value is numbers between 1-1000
http://mysite.com?one=2&two=4&number=2
http://mysite.com?one=2&two=4&four=4&number=124
http://mysite.com?one=2&three=4&number=9
http://mysite.com?two=4&number=242
http://mysite.com?one=2&two=4&number=52
How can i remove from this parameter and value with PHP? I would like receive:
http://mysite.com?one=2&two=4
http://mysite.com?one=2&two=4&four=4
http://mysite.com?one=2&three=4
http://mysite.com?two=4
http://mysite.com?one=2&two=4
Try this:
$str = 'http://mysite.com?one=2&two=4&number=2';
$url = parse_url($str);
parse_str($url['query'], $now );
unset($now['number']);
foreach($now as $key=>$value) :
if(is_bool($value) ){
$now[$key] = ($value) ? 'true' : 'false';
}
endforeach;
$options_string=http_build_query($now);
echo $url = 'http://mysite.com?'.$options_string;
Reference : PHP function to build query string from array - not http build query
Like this
$urls = '
http://mysite.com?one=2&two=4&number=2
http://mysite.com?one=2&two=4&four=4&number=124
http://mysite.com?one=2&three=4&number=9
http://mysite.com?two=4&number=242
http://mysite.com?one=2&two=4&number=52
';
echo '<pre>';
echo preg_replace('#&number=\d+#', '', $urls);
you can build a redirection after building a new URL with $_GET['one']
Use bellow steps,this is clear aproach
1- Parse the url into an array with parse_url()
2- Extract the query portion, decompose that into an array
3- Delete the query parameters you want by unset() them from the array
4- Rebuild the original url using http_build_query()
hope this help you
You could use parse_str() which parses the string into variables. In that way you can separate them easily
I wrote example of code.
<?php
$arr = array();
$arr[] = 'http://mysite.com?one=2&two=4&number=2';
$arr[] = 'http://mysite.com?one=2&two=4&four=4&number=124';
$arr[] = 'http://mysite.com?one=2&three=4&number=9';
$arr[] = 'http://mysite.com?two=4&number=242';
$arr[] = 'http://mysite.com?one=2&two=4&number=52';
function remove_invalid_arguments(array $array_invalid, $urlString)
{
$info = array();
parse_str($urlString, $info);
foreach($array_invalid as $inv)
if(array_key_exists($inv,$info)) unset($info[$inv]);
$ret = "";
$i = 0;
foreach($info as $k=>$v)
$ret .= ($i++ ? "&" : ""). "$k=$v"; //maybe urlencode also :)
return $ret;
}
//usage
$invalid = array('number'); //array of forbidden params
foreach($arr as $k=>&$v) $v =remove_invalid_arguments($invalid, $arr[1]);
print_r($arr);
?>
Working DEMO
If "&number=" is ALWAYS after the important parameters, I'd use str_split (or explode).
The more sure way is to use parse_url(),parse_str() and http_build_query() to break the URLs down and put them back together.
As per example of your url -
$s='http://mysite.com?one=2&two=4&number=2&number2=200';
$temp =explode('&',$s);
array_pop($temp);
echo $newurl = implode("&", $last);
Output is :http://mysite.com?one=2&two=4&number=2
Have a look at this one using regex: (as an alternative, preferably use a parser)
(.+?)(?:&number=\d+)
Assuming &number=2 is the last parameter. This regex will keep the whole url except the last parameter number

clearing the link id

if we have
$id = 39827-key1-key2-key3
and we want to show only the number or anything before (-)
then by using
$realid = array_shift(explode("-", $id));
we will get echo $realid; // 39827
Now my problem is as following !
if we have $id = key1/key2
and i want any way that remove the whole part key1/ and gives me only key2
how can i do it?
Ok, from your comment above, I'm assuming you want to do something like:
$id = "key1/key2";
$result = ???;
// Now $result=="$key2"
Why not just:
$parts = explode("/", $id);
$result = $parts[1];
Using the strstr() function, which was created exactly for things like this:
$id = 'key1/key2';
$realid = strstr($id, '/', true);
Do note that you have to be running PHP 5.3 or newer for this to work.
confusing question. my interpretation for $rawId containing the '/' char:
$rawId = 'key1/key2';
$realId = substr($rawId, 1 + strpos($rawId, '/')); // key2
Yet another way:
$result = implode('', array_slice(explode('/', $id), 1, 1));

Take a part of a string (PHP)

We are trying to get certain parts of a String.
We have the string:
location:32:DaD+LoC:102AD:Ammount:294
And we would like to put the information in different strings. For example $location=32 and $Dad+Loc=102AD
The values vary per string but it will always have this construction:
location:{number}:DaD+LoC:{code}:Ammount:{number}
So... how do we get those values?
That would produce what you want, but for example $dad+Loc is an invalid variable name in PHP so it wont work the way you want it, better work with an array or an stdClass Object instead of single variables.
$string = "location:32:DaD+LoC:102AD:Ammount:294";
$stringParts = explode(":",$string);
$variableHolder = array();
for($i = 0;$i <= count($stringParts);$i = $i+2){
${$stringParts[$i]} = $stringParts[$i+1];
}
var_dump($location,$DaD+LoC,$Ammount);
Easy fast forward approach:
$string = "location:32:DaD+LoC:102AD:Ammount:294";
$arr = explode(":",$string);
$location= $arr[1];
$DaD_LoC= $arr[3];
$Ammount= $arr[5];
$StringArray = explode ( ":" , $string)
By using preg_split and mapping the resulting array into an associative one.
Like this:
$str = 'location:32:DaD+LoC:102AD:Ammount:294';
$list = preg_split('/:/', $str);
$result = array();
for ($i = 0; $i < sizeof($list); $i = $i+2) {
$result[$array[$i]] = $array[$i+1];
};
print_r($result);
it seems nobody can do it properly
$string = "location:32:DaD+LoC:102AD:Ammount:294";
list(,$location,, $dadloc,,$amount) = explode(':', $string);
the php function split is deprecated so instead of this it is recommended to use preg_split or explode.
very useful in this case is the function list():
list($location, $Dad_Loc, $ammount) = explode(':', $string);
EDIT:
my code has an error:
list(,$location,, $Dad_Loc,, $ammount) = explode(':', $string);

Categories