sorry if my question was stupid, please someone help me to fix this issue.
i have string like
$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/9/";
this $str_value is dynamic , it will change each page. now i need to replace 9 in this string as 10. add integer 1 and replace
for example if the $str_value = "http://99.99.99.99/var/test/src/158-of-box.html/251/"
then output should be
http://99.99.99.99/var/test/src/158-of-box.html/252/
i tried to replace using preg_match but i m getting wrong please somesone help me
$str = preg_replace('/[\/\d+\/]/', '10',$str_value );
$str = preg_replace('/[\/\d+\/]/', '[\/\d+\/]+1',$str_value );
Thank's for the answer, #Calimero! You've been faster than me, but I would like to post my answer, too ;-)
Another possibilty is to fetch the integer by using a group. So you don't need to trim $matches[0] to remove the slashes.
$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/9/";
$str = preg_replace_callback('/\/([\d+])\//', function($matches) {
return '/'.($matches[1]+1).'/';
}, $str_value);
echo $str;
You need to use a callback to increment the value, it cannot be done directly in the regular expression itself, like so :
$lnk= "http://99.99.99.99/var/test/src/158-of-box.html/9/";
$lnk= preg_replace_callback("#/\\d+/#",function($matches){return "/".(trim($matches[0],"/")+1)."/";},$lnk); // http://99.99.99.99/var/test/src/158-of-box.html/10/
Basically, the regexp will capture a pure integer number enclosed by slashes, pass it along to the callback function which will purge the integer value, increment it, then return it for replacement with padded slashes on each side.
I'd suggest also another approach based on explode and implode instead of doing any regexp stuff. In my opinion this is more readable.
$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/11/";
// explode the initial value by '/'
$explodedArray = explode('/', $str_value);
// get the position of the page number
$targetIndex = count($explodedArray) - 2;
// increment the value
$explodedArray[$targetIndex]++;
// implode back the original string
$new_str_value = implode('/', $explodedArray);
Related
I know it may sound as a common question but I have difficulty understanding this process.
So I have this string:
http://domain.com/campaign/tgadv?redirect
And I need to get only the word "tgadv". But I don't know that the word is "tgadv", it could be whatever.
Also the url itself may change and become:
http://domain.com/campaign/tgadv
or
http://domain.com/campaign/tgadv/
So what I need is to create a function that will get whatever word is after campaign and before any other particular character. That's the logic..
The only certain thing is that the word will come after the word campaign/ and that any other character that will be after the word we are searching is a special one ( i.e. / or ? )
I tried understanding preg_match but really cannot get any good result from it..
Any help would be highly appreciated!
I would not use a regex for that. I would use parse_url and basename:
$bits = parse_url('http://domain.com/campaign/tgadv?redirect');
$filename = basename($bits['path']);
echo $filename;
However, if want a regex solution, use something like this:
$pattern = '~(.*)/(.*)(\?.*)~';
preg_match($pattern, 'http://domain.com/campaign/tgadv?redirect', $matches);
$filename = $matches[2];
echo $filename;
Actually, preg_match sounds like the perfect solution to this problem. I assume you are having problems with the regex?
Try something like this:
<?php
$url = "http://domain.com/campaign/tgadv/";
$pattern = "#campaign/([^/\?]+)#";
preg_match($pattern, $url, $matches);
// $matches[1] will contain tgadv.
$path = "http://domain.com/campaign/tgadv?redirect";
$url_parts = parse_url($path);
$tgadv = strrchr($url_parts['path'], '/');
You don't really need a regex to accomplish this. You can do it using stripos() and substr().
For example:
$str = '....Your string...';
$offset = stripos($str, 'campaign/');
if ( $offset === false ){
//error, end of h4 tag wasn't found
}
$offset += strlen('campaign/');
$newStr = substr($str, $offset);
At this point $newStr will have all the text after 'campaign/'.
You then just need to use a similar process to find the special character position and use substr() to strip the string you want out.
You can also just use the good old string functions in this case, no need to involve regexps.
First find the string /campaign/, then take the substring with everything after it (tgadv/asd/whatever/?redirect), then find the next / or ? after the start of the string, and everything in between will be what you need (tgadv).
I need to check a string using PHP for a particular text component and replace the value if it is present with a new value. For example I might have a string like this:
?customerID=12345&recid=65&skip=20&type=job
I need to locate the "&skip=20" (it won't always = 20, it could be any number like 20, 80, 100, etc) substring and replace the "20" value with a new value from a variable ($newValue). So if that string was present and $newValue = 40 the new string would be:
?customerID=12345&recid=65&skip=40&type=job
If the string was:
?customerID=12345&recid=65&skip=160&type=job
the new string would be ($newValue = 180):
?customerID=12345&recid=65&skip=180&type=job
I'm pretty sure I should be using these functions - strpos, preg_match, preg_replace - but I've spent way too long on this and don't appear to be getting any closer. If anyone can show me how to use these or other functions to find the substring and replace the value that would be much appreciated.
Try preg_replace_callback
<?php
$str = "?customerID=12345&recid=65&skip=20&type=job";
$newStr = preg_replace_callback("/skip=([0-9]+)/i", "doIt", $str)
function doIt($match){
return $match[1] + 20;
}
I have this string:
a:3:{i:0;i:2;i:1;i:3;i:2;i:4;}
I want to get number between "a:" and ":{" that is "3".
I try to user substr and strpos but no success.
I'm newbie in regex , write this :
preg_match('/a:(.+?):{/', $v);
But its return me 1.
Thanks for any tips.
preg_match returns the number of matches, in your case 1 match.
To get the matches themselves, use the third parameter:
$matches = array();
preg_match(/'a:(\d+?):{/', $v, $matches);
That said, I think the string looks like a serialized array which you could deserialize with unserialize and then use count on the actual array (i.e. $a = count(unserialize($v));). Be careful with userprovided serialized strings though …
If you know that a: is always at the beginning of the string, the easiest way is:
$array = explode( ':', $string, 3 );
$number = $array[1];
You can use sscanfDocs to obtain the number from the string:
# Input:
$str = 'a:3:{i:0;i:2;i:1;i:3;i:2;i:4;}';
# Code:
sscanf($str, 'a:%d:', $number);
# Output:
echo $number; # 3
This is often more simple than using preg_match when you'd like to obtain a specific value from a string that follows a pattern.
preg_match() returns the number of times it finds a match, that's why. you need to add a third param. $matches in which it will store the matches.
You were not too far away with strpos() and substr()
$pos_start = strpos($str,'a:')+2;
$pos_end = strpos($str,':{')-2;
$result = substr($str,$pos_start,$pos_end);
preg_match only checks for appearance, it doesn't return any string.
I'm trying to trim some youtube URLs that I am reading in from a playlist. The first 3 work fine and all their URLs either end in caps or numbers but this one that ends in a lower case g is getting trimmed one character shorter than the rest.
for ($z=0; $z <= 3; $z++)
{
$ythref2 = rtrim($tubeArray["feed"]["entry"][$z]["link"][0]["href"], '&feature=youtube_gdata');
The URL is http://www.youtube.com/watch?v=CuE88oVCVjg&feature=youtube_gdata .. and it should get trimmed down to .. http://www.youtube.com/watch?v=CuE88oVCVjg but instead it is coming out as http://www.youtube.com/watch?v=CuE88oVCVj.
I think it may be the ampersand symbol but I am not sure.
The second argument to rtrim is a list of characters to remove, not a string to remove.
You might want to use str_replace, or use parse_url and parse_str to get arrays of the components of the URL and the components of the query string, like "v".
Untested example code:
$youtube_url = 'http://www.youtube.com/watch?v=CuE88oVCVjg&feature=youtube_gdata';
$url_bits = parse_url($youtube_url);
$query_string = array();
parse_str($url_bits['query'], $query_string);
$video_identifier = $query_string['v']; // "CuE88oVCVjg"
$rebuilt_url = 'http://www.youtube.com/watch?v=' . $video_identifier;
No, it's the g in the second argument. rtrim() does not remove a string from the end, it removes any characters given in the second argument. Use preg_replace() or substr() instead.
I have number like 9843324+ and now I want to get rid of + at the end and only have 9843324 and so how should I do this in php ?
Right now I am doing $customer_id = explode('+',$o_household->getInternalId); also $o_household->getInternalId returns me 9843324+ but I want 9843324, how can I achieve this ?
Thanks.
if you just want to pop the + off the end, use substr.
$customer_id = substr($o_household->getInternalId, 0, -1);
or rtrim
$customer_id = rtrim($o_household->getInternalId, "+");
You can use a regeular expression to remove anything that isn't a number
$newstr = preg_replace("/[^0-9]+/","",$str);
$customer_id = rtrim ( $o_household->getInternalId, '+' );
rtrim function reference
rtrim removes the characters in the second argument (+ only in this case) from the end of a string.
In case there is no + at the end of the string, this won't mess up your value like substr.
This solution is obviously more readable and faster than, let's say preg_replace too.
you could use intval($o_household->getInternalId)
Is there a reason you need to use explode? i would just use substr as Andy suggest or str_replace. Either would work for the example you provided.
You can use intval to get the integer value of a variable, if possible:
echo intval($str);
Be aware that intval will return 0 on failure.