i want to find the string after "-" which is exactly in 3rd position, If it doesn't find the "-" it should get the whole string.
sample data are
TT-people // get people
1V-NEWTET // get NEWTET
ZZ-YESforTHE // get YESforTHE
Computer // get Computer
T-Book // get T-Book
I tried as
$result=preg_match_all("/^[a-zA-Z0-9]2-(\s\w*)/",$data,$networkID);
echo $networkID[0][1]
please rectify my error.
[a-zA-Z0-9]2
The 2 here just matches the character “2”. Looks like you meant {2}.
To reflect your updated question, it should look like this:
$result = preg_match_all('/^(?:[a-zA-Z0-9]{2}-)?(\s\w*)/', $data, $networkID);
echo $networkID[0][1];
The ? makes the group optional.
if its a single line if text you can do:
if(substr($string, 2, 1) === "-"){
echo substr($string, 3);
}else{
echo $string;
}
Related
My questions is somewhat based off this:
How can I get the last 7 characters of a PHP string?
Mine is similar. I need to get the last x characters of a string and to stop when I reach "-"
for example, I have a booking code:
N-903
and I can get the last 3 characters like so:
$booking_Code = N-903
$booking_Code = substr($booking_Code, -3);
and the result will be:
903
This number however will increase, so I expect to see booking codes like:
N-1001
N-22520
N-201548
so the code:
substr($booking_Code, -3);
would become useless. Is there any way to use "-" as a delimiter? I think that's the correct term to use. because the number that's generated will always come after the hyphen "-". Any help would be greatly appreciated
try this
<?php
$tmpArray = explode("-",$mystr);
echo $tmpArray[1];
?>
You might want to refer to explode function in php.
As an alternative, you could also use strrchr in conjunction with the substr you have:
$booking_Code = 'N-903';
$booking_Code = substr(strrchr($booking_Code, '-'), 1);
echo $booking_Code; // 903
I would like to figure out, how to check if the second to last character of a string is numeric.
My string is:
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
The URL is something like: http://www.domain.com/2/,http://www.domain.com/3/ and so on..
Is it possible to figure out if a number exists at the end of the URL before the last back slash / ?
Something like:
if (is_numeric($url, second-to-last-character)) {
// Do real stuff
} else {
// Do whatever
}
What about regexes ?
if (!preg_match('#/\d+/?$#', $url))
// There is no numeric at the end, abort !
I propose this because you won't know how many digits your id will have, so you can't just test the second-to-last character.
$fullurl = explode('/',$_SERVER['SCRIPT_NAME']);
$last = $fullurl[count($fullurl)-1];
//echo $last;
if(is_int($last))
echo "integer";
else
echo "Not integer";
You want to use substr. You can use this to get the second to last character.
http://php.net/manual/en/function.substr.php
is_numeric(substr($url, -2, 1);
if (is_numeric(substr($url, -2,1) ) {
should do you, You dont need the regex
use substr
if(is_numeric(substr($url,-2,1))){
//dosomething
}else{
echo "Invalid URL!";
}
in substr, the first parameter is the string, the second one is the offset, if the offset is negative, it will start at the end and go backwards, and the last one is the length. If not specified, it will go to the end of the string. So if you wanted to get the last tow characters, you would do substr($url,-2)
$url='http://www.domain.com/2/,http://www.domain.com/3/';
if(is_numeric (substr($url,-2,1))){
echo "This is number";
}else{
echo "This is not number";
}
I don't want to get offtopic, but when i'm dealing with URLs usually i delete ending slashes using
$url = rtrim($url, '/');
http://www.php.net/manual/en/function.rtrim.php
Usually you won't need that slash and it'll be messy when exploding the URL. You can use the substr() function as mentioned by previous answers to get the last character of the string then. AFAIK the substr() function is faster than using regular expressions for such a simple task.
if (is_numeric(substr($url, -1)) {}
edit
i just realized that if you are dealing with values > 9 you will be in trouble.
Better get the whole number as mentioned in another answer. If you prefer strange looking code with slightly better performance you can use that one instead of explode():
$value = strrev(strtok(strrev($url), '/'));
if (is_numeric($value)) {}
So this is my code: i want get agm from http://example.com?agm=12345 end substr agm to get 12
echo $_GET["agm"] if substr(["agm"], 0, -3);
You have lots of errors in your code.
echo $_GET["agm"] // you should end it with ;
if substr(["agm"], 0, -3);
You should:
Use parenthesis for a criterion, so if(...)
You should use $_GET["agm"] instead of ["agm"]
You can use substr($_GET["agm"],0,2) to take first two characters.
Please refer to manual examples of substr() function.
Do you want to get the value of agm or just the...text? If it's just the text "agm", just write it out as a string...
$str = "agm";
echo $str; // agm
Otherwise, to get the contents of "agm"
$data = $_GET['agm'];
echo $data; // 12345
If that's not what you're after, I really haven't a clue what you're asking.
I know there are lots of tutorials and question on replacing something in a string.
But I can't find a single one on what I want to do!
Lets say I have a string like this
$string="Hi! [num:0]";
And an example array like this
$array=array();
$array[0]=array('name'=>"na");
$array[1]=array('name'=>"nam");
Now what I want is that PHP should first search for the pattern like [num:x] where x is a valid key from the array.
And then replace it with the matching key of the array. For example, the string given above should become: Hi! na
I was thinking of doing this way:
Search for the pattern.
If found, call a function which checks if the number is valid or not.
If valid, returns the name from the array of that key like 0 or 1 etc.
PHP replaces the value returned from the function in the string in place of the pattern.
But I can't find a way to execute the idea. How do I match that pattern and call the function for every match?
This is just the way that I am thinking to do. Any other method will also work.
If you have any doubts about my question, please ask in comments.
Try this
$string="Hi! [num:0]";
$array=array();
$array[0]=array('name'=>"na");
$array[1]=array('name'=>"nam");
echo preg_replace('#(\!)?\s+\[num:(\d+)\]#ie','isset($array[\2]) ? "\1 ".$array[\2]["name"] : " "',$string);
If you don't want the overhead of Regex, and your string format remains same; you could use:
<?php
$string="Hi! [num:0]";
echo_name($string); // Hi John
echo "<br />";
$string="Hello! [num:10]";
echo_name($string); // No names, only Hello
// Will echo Hi + Name
function echo_name($string){
$array=array();
$array[0]=array('name'=>"John");
$array[1]=array('name'=>"Doe");
$string = explode(" ", $string);
$string[1] = str_replace("[num:", "", $string[1]);
$string[1] = str_replace("]", "", $string[1]);
if(array_key_exists($string[1], $array)){
echo $string[0]." ".$array[$string[1]]["name"];
} else {
echo $string[0]." ";
}
}// function echo_sal ENDs
?>
Live: http://codepad.viper-7.com/qy2uwW
Assumptions:
$string always will have only one space, exactly before [num:X].
[num:X] is always in the same format.
Of course you could skip the str_replace lines if you could make your input to simple
Hi! 0 or Hello! 10
OK, so there is a page I'm querying on another server that returns a comma separated list of two values. Something it would return would be:
850,640
I have some PHP code that calls file_get_contents on that page and needs to do some numeric calculations based on the two values.
No matter what I try, I can't seem to get an int value out of this.
$res = trim(file_get_contents('http://thatURL/'));
echo "X" . $res . "X<br/>";
list($x,$y) = array_map(create_function('$a', 'return (int)$a;'), explode(',', $res));
echo "X:$x";
results in the output:
X 850,640 X
X:0
Note the spaces before and after the comma separated values(how the hell? I trim'd them!) and that $x is assigned the value 0.
What am I doing wrong here?
What am I doing wrong here?
Nothing, as far as I can see, which indicates that the content of $res is not quite what you expect. Could you change the first echo to:
echo htmlentities($res);
My guess is $res contains some un-printed characters, for example, it is actually:
<span> </span>850,640<span> </span>
or
850,640
Try the following. The array_map and llamda function are arguably overkill for your usage.
$res = " 850,640 ";
echo "X" . $res . "X<br/>";
list($x,$y) = explode(',', trim($res));
echo "X:" . (int)$x;
echo "Y:" . (int)$y;
Worked for me, but I'm not using file_get_contents(). If that doesn't work, something else is being output by the page.
PHP is not a typed language. Use intval to convert a string to integer.
Correction: it is a loosely typed language! That's what I meant!
Since I was using file_get_contents() on a URL, there was some HTML being put in as well that I didn't notice in my echo because it parsed out... just empty body and html tags. Oops!