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;
}
Related
I got this result from mysql query using php:
chris123
I want to separate chris from 123 because I am going to use the value of int for operation.
$char=string('chris123');
$int=int('chris123');
How am I able to do it in PHP? Not PDO. Not so familiar with it. Thanks.
If you know the non-number parts are always going to be lowercase characters, you can do this:
$str = 'chris123';
$num = trim($str, 'a..z');
If you also want it to be an actual integer, you can cast it:
$str = 'chris123';
$num = (int) trim($str, 'a..z');
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);
This may be a dupe, but I cannot seem to find a thread which matches this issue. I want to remove all chars from a string after a given sub-string - but the chars and the number of chars after the sub-string is unknown. Most solutions I have found seem to only work for removing the given sub-string itself or a fixed length after a given sub-string.
I have
$str = preg_replace('(.gif*)','.gif$',$str);
Which locates 'blahblah.gif?12345' ok, but I cannot seem to remove the chars after the sub-string '.gif'. I read that $ denotes EOS so I thought this would work, but apparently not. I also tried
'.gif$/'
and simply
'.gif'
It can be done without regex:
echo substr('blahblah.gif?12345', strpos('blahblah.gif?12345', '.gif') + 4);
// returns ?12345 this is the length of the substring ^
So the code is:
$str = 'original string';
$match = 'matching string';
$output = substr($str, strpos($str, $match) + strlen($match));
Ok, now I'm not sure if you want to keep the first or the second part of the string. Anyway, here's the code for keeping the first part:
echo substr('blahblah.gif?12345', 0, strpos('blahblah.gif?12345', '.gif') + 4);
// returns blahblah.gif ^ this is the key
And the full code:
$str = 'original string';
$match = 'matching string';
$output = substr($str, 0, strpos($str, $match) + strlen($match));
See the both examples work here: http://ideone.com/Ge30rY
Assuming (from OP's comment) that you are working with actual URLs as your source string, I believe that the best course of action here would be to use PHP's built-in functionality for working with and parsing URLs. You do this by using the parse_url() function:
(PHP 4, PHP 5)
parse_url — Parse a URL and return its components
This function parses a URL and returns an associative array containing any of the various components of the URL that are present.
This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly.
From your example: www.page.com/image.gif?123 (or even just image.gif?123) using parse_url() will look something like this:
var_dump( parse_url( "www.page.com/image.gif?123" ) );
array(2) {
["path"]=>
string(22) "www.page.com/image.gif"
["query"]=>
string(3) "123"
}
As you can see, without the need for regular expressions or string manipulations we have broken up the URL into it's separate components. No need to re-invent the wheel. Nice and clean :)
You could do this:
$str = "somecontent.gif?anddata";
$pattern = ".gif";
echo strstr($str,$pattern,true).$pattern;
// Set up string to search through
$haystack = "blahblah.gif?12345";
// Determine substring and length of it
$needle = ".gif";
$length = strlen($needle);
// Find position of last substring
$location = strrpos($haystack, $needle);
// Use location of last occurence + it's length to get new string
$newtext = substr($haystack, 0, $location+$length);
I have a text string that is set in a variable to a value like these:
$str = 'type=showall'
or
$str = 'type=showall&skip=20'
$str = 'type=showall&skip=40'
$str = 'type=showall&skip=60'
and so on.
I need to check to see if there is a "skip" value present in the string, and if so replace it with a new number that is stored in a $newSkip variable and keep the string the same except for the change to the skip value.
For example if the string was:
$str = 'type=showall&skip=20'
and
$newSkip = 40
then I would like this to be returned:
$str = 'type=showall&skip=40'
If there was no skip value:
$str = 'type=showall'
and
$newSkip = 20
then I would like this to be returned:
$str = 'type=showall&skip=20'
I'm fairly new to PHP so still finding my way with the various functions and not sure which one/s are the best ones to use in this scenario when the text/value you're looking for may/may not be in the string.
PHP has a handy function called parse_str() which accepts a string similar to the one you have, and returns an array with key/value pairs. You'll then be able to inspect specific values and make the changes you need.
$str = 'type=showall&skip=20';
// this will parse the string and place the key/value pairs into $arr
parse_str($str,$arr);
// check if specific key exists
if (isset($arr['skip'])){
//if you need to know if it was there you can do stuff here
}
//set the newSkip value regardless
$arr['skip'] = $newSkip;
echo http_build_query($arr);
The http_build_query function will return the array into the same URI format that you started with. This function also encodes the final string so if you want to see the decoded version, you'll have to send it through urldecode().
References -
parse_str()
http_build_query()
I'm having trouble with PHP text parsing
I have a txt file which has this kind of information:
sometext::sometext.0 = INTEGER: 254
What i need is to get the last value of 254 as variable in PHP.
in this txt file this last value can change from 0 to 255
"sometext::sometext.0 = INTEGER: " this part doesn't change at all.
It has a length of 36 symbols, so i need get with PHP what is after 36 symbol into variable.
Thank you.
Try using sscanf:
$string = "sometext::sometext.0 = INTEGER: 254";
sscanf($string, "sometext::sometext.0 = INTEGER: %d", $number);
echo $number;
Demo: http://codepad.org/Ash2QHvI
Perhaps substr() will do?
$text = "sometext::sometext.0 = INTEGER: 254";
print substr($text, 37);
See it in action here (adjusted to match your sample data): http://codepad.org/5Ikt3kRh
Try fgets for reading a file.
For the parsing I use split. I wrote an example here. But sscanf seems to be the better option.
Since you know the string is always going to be of that form you can use the substr() function to extract the part of the string you want. Then use intval() to make it an integer if needed.
Note: My count shows that the number you're trying to get starts at the 33rd position (which becomes 32 below, as substr is 0 based), not the 36th.
You can get what you want with:
$the_str = 'sometext::sometext.0 = INTEGER: 254';
$num = intval(substr($the_str, 32));