I have variables like this:
$path1 = "<span class='span1' data-id=2>lorem ipsum</span>";
$path2 = "<span class='span2' data-id=14>lorem ipsum</span>";
I need to get value of data-id but I think it's not possible in php.
Maybe is possible to get last integer in a string ?
Something like:
$a = $path1.lastinteger(); // 2
$b = $path2.lastinteger(); // 14
Any help?
You could use a simple regex:
/data-id=[\"\']([1-9]+)[\"\']/g
Then you can build this function:
function lastinteger($item) {
preg_match_all('/data-id=[\"\']([1-9]+)[\"\']/',$item,$array);
$out = end($array);
return $out[0];
}
Working DEMO.
The full code:
function lastinteger($item) {
preg_match_all('/data-id=[\"\']([1-9]+)[\"\']/',$item,$array);
$out = end($array);
return $out[0];
}
$path1 = "<span class='span1' data-id=2>lorem ipsum</span>";
$path2 = "<span class='span2' data-id=14>lorem ipsum</span>";
$a = lastinteger($path1); //2
$b = lastinteger($path2); //14
References:
preg_match_all()
end()
Tutorial for regex: tutorialspoint.com
Good tool to create regex: regexr.com
If you'd rather not use a regular expression you can use the DOM API:
$dom = DOMDocument::loadHTML($path2);
echo $dom->getElementsByTagName('span')[0]->getAttribute('data-id');
Depending on how those variables get set, one solution could be to get the integer first and then inject it into the paths:
$dataId = 2;
$path1 = "<span class='span1' data-id='$dataId'>lorem ipsum</span>";
(Note that I added quotes around the data-id value, otherwise your HTML is invalid.)
If you aren't building the strings yourself, but need to parse them, I would not simply get the last integer. The reason is that you might get a tag like this:
<span class='span1' data-id='4'>Happy 25th birthday!</span>
In that case, the last integer in the string is 25, which isn't what you want. Instead, I would use a regular expression to capture the value of the data-id attribute:
$path1 = "<span class='span1' data-id='2'>lorem ipsum</span>";
preg_match('/data-id=\'(\d+)\'/', $path1, $matches);
$dataId = $matches[1];
echo($dataId); // => 2
I think that you should use regex, for example:
<?php
$paths = [];
$paths[] = '<span class=\'span1\' data-id=2>lorem ipsum dolor</span>';
$paths[] = '<span class=\'span2\' data-id=14>lorem ipsum</span>';
foreach($paths as $path){
preg_match('/data-id=([0-9]+)/', $path, $data_id);
echo 'data-id for '.$path.' is '.$data_id[1].'<br />';
}
This will output:
data-id for lorem ipsum dolor is 2
data-id for lorem ipsum is 14
function find($path){
$countPath = strlen($path);
for ($i = 0; $i < $countPath; $i++) {
if (substr($path, $i, 3) == "-id") {
echo substr($path, $i + 4, 1);
}
}}find($path1);
Wrote an appropiate function for this purpose.
function LastNumber($text){
$strlength = strlen($text); // get length of the string
$lastNumber = ''; // this variable will accumulate digits
$numberFound = 0;
for($i = $strlength - 1; $i > 0; $i--){ // for cicle reads your string from end to start
if(ctype_digit($text[$i])){
$lastNumber = $lastNumber . $text[$i]; // if digit is found, it is added to last number string;
$numberFound = 1; // and numberFound variable is set to 1
}else if($numberFound){ // if atleast one digit was found (numberFound == 1) and we find non-digit, we know that last number of the string is over so we break from the cicle.
break;
}
}
return intval(strrev($lastNumber), 10); // strrev reverses last number string, because we read original string from end to start. Finally, intval function converts string to integer with base 10
}
I know this has been answered, but if you really want to get the last int in a line without referring specifically to attributes or tag names, consider using this.
$str = "
asfdl;kjas;lkjfasl;kfjas;lf 999 asdflkasjfdl;askjf
<span class='span1' data-id=2>lorem ipsum</span>
<span class='span2' data-id=14>lorem ipsum</span>
Look at me I end with a number 1234
";
$matches = NULL;
$num = preg_match_all('/(.*)(?<!\d)(\d+)[^0-9]*$/m', $str, $matches);
if (!$num) {
echo "no matches found\n";
} else {
var_dump($matches[2]);
}
It will return an array from a multiline input of the last integers for each line:
array(4) {
[0] =>
string(3) "999"
[1] =>
string(1) "2"
[2] =>
string(2) "14"
[3] =>
string(4) "1234"
}
Related
I want to iterate a string in the manner that after each character there should be a space and there will be new string(word) as per the main string character count.
For example
If I put the string "v40eb" as an input. Then Output be something like below.
v 40eb
v4 0eb
v40 eb
v40e b
OR
In Array form like below.
[0]=>v 40eb[1]=>v4 0eb[2]=>v40 eb[3]=>v40e b
I am using PHP.
Thanks
Well, you can divide the process of putting a space into 2 parts.
Get first part of the substring, append a space.
Get second part of the substring and join them together.
Use substr() to get a substring of a string.
Snippet:
<?php
$str = "v40eb";
$result = [];
$len = strlen($str);
for($i=0;$i<$len;++$i){
$part1 = substr($str,0,$i+1);
if($i < $len-1) $part1 .= " ";
$part2 = substr($str,$i+1);
$result[] = $part1 . $part2;
}
print_r($result);
Demo: https://3v4l.org/XGN0a
You could simply loop over the char positions and use substr to get the two parts for each:
$input = 'v40eb';
$combinations = [];
for ($charPos = 1, $charPosMax = strlen($input); $charPos < $charPosMax; $charPos++) {
$combinations[] = substr($input, 0, $charPos) . ' ' . substr($input, $charPos);
}
print_r($combinations);
Demo: https://3v4l.org/EeT1V
$input = 'v40eb';
for($i = 1; $i< strlen($input); $i++) {
$array = str_split($input);
array_splice($array, $i, 0, ' ');
$output[] = implode($array);
}
print_r($output);
Dont forget to check the codec. You might use mb_-prefix to use the multibyte-functions.
Given the string "123456789#test.com", I'm trying to remove from the '#' symbol on, I just want the numbers. I've been trying to split the string into an array and remove array elements based on if that element is numeric, then merging the elements back into a string. My code...
$employee_id = "123456789#test.com";
$employee_id_array = str_split($employee_id);
for($i = 0; $i < sizeof($employee_id_array); $i++) {
if(is_numeric($employee_id_array[$i]) === false) {
unset($employee_id_array[$i]);
$employee_id_array = array_values($employee_id_array);
}
}
$employee_id = implode($employee_id_array);
echo "employee id: $employee_id";
What it should print out: 123456789
What it actually prints out: 123456789ts.o
What am I missing?
echo strstr($employee_id, '#', true);
To get all the numbers in employee_id string:
$employee_id = "123456789#test.com";
preg_match_all('!\d+!', $employee_id, $matches);
echo $matches[0][0];
This will return all the numbers in the provided string.
If you want to get string before # in employee_id then you can try this:
$employee_id = "123456789#test.com";
$output = explode('#', $employee_id);
echo $output[0];
I had a look at regular expressions in PHP but I don't really understand how they work.
I have various strings like "1-title" , "1-1-secondTitle", "1-2-otherTitle", This goes up to three level ("1-2-1-text"), so on every string I have this formating and I would like to check if there is one, two or three number before the string starts and then output "0", "1" or "2".
So to make it clearer
"1-index" should return "0"
"3-1-text" should return "1"
"5-2-1-otherTitle" should return "2"
is it possible to check the number of char before the first letter on a string?
Alternaatively, if you dont want to use regex, then, you could just iterate thru the string and overwrite the index. Consider this example:
$string = '5-2-1-otherTitle';
$string = str_ireplace('-', '', $string);
$index = null;
for($x = 0; $x < strlen($string); $x++) {
if(is_numeric($string[$x])) {
$index = $x;
}
}
echo $index; // outputs 2
// works
// echo preg_match_all("/[0-9]/", $string) - 1;
I have a string I get from a website.
A portion of the string is "X2" I want to add +1 to 2.
The entire string I get is:
20120815_00_X2
What I want is to add the "X2" +1 until "20120815_00_X13"
You can do :
$string = '20120815_00_X2';
$concat = substr($string, 0, -1);
$num = (integer) substr($string, -1);
$incremented = $concat . ($num + 1);
echo $incremented;
For more informations about substr() see => documentation
You want to find the number at the end of your string and capture it, test for a maximum value of 12 and add one if that's the case, so your pattern would look something like:
/(\d+)$/ // get all digits at the end
and the whole expression:
$new = preg_replace('/(\d+)$/e', "($1 < 13) ? ($1 + 1) : $1", $original);
I have used the e modifier so that the replacement expression will be evaluated as php code.
See the working example at CodePad.
This solution works (no matter what the number after X is):
function myCustomAdd($string)
{
$original = $string;
$new = explode('_',$original);
$a = end($new);
$b = preg_replace("/[^0-9,.]/", "", $a);
$c = $b + 1;
$letters = preg_replace("/[^a-zA-Z,.]/", '', $a);
$d = $new[0].'_'.$new[1].'_'.$letters.$c;
return $d;
}
var_dump(myCustomAdd("20120815_00_X13"));
Output:
string(15) "20120815_00_X14"
I have randomly created strings such as
H*P2[-%-3:5RW0j*;k52vedsSQ5{)ROkb]P/*DZTr*-UX4sp
What I want to do is get a count of all Caps, lower case, numeric and special characters in each string as they are generated.
I am looking for an output similar to
Caps = 5
Lower = 3
numneric = 6
Special = 4
Fictitious values of course.
I have gone through the php string pages using count_char, substr_count etc but cant find what I am looking for.
Thank you
preg_match_all() returns the number of occurences of a match. You'll just need to fill in the regex correlates for each bit of info you want. For example:
$s = "Hello World";
preg_match_all('/[A-Z]/', $s, $match);
$total_ucase = count($match[0]);
echo "Total uppercase chars: " . $total_ucase; // Total uppercase chars: 2
You can use the ctype-functions
$s = 'H*P2[-%-3:5RW0j*;k52vedsSQ5{)ROkb]P/*DZTr*-UX4sp';
var_dump(foo($s));
function foo($s) {
$result = array( 'digit'=>0, 'lower'=>0, 'upper'=>0, 'punct'=>0, 'others'=>0);
for($i=0; $i<strlen($s); $i++) {
// since this creates a new string consisting only of the character at position $i
// it's probably not the fastest solution there is.
$c = $s[$i];
if ( ctype_digit($c) ) {
$result['digit'] += 1;
}
else if ( ctype_lower($c) ) {
$result['lower'] += 1;
}
else if ( ctype_upper($c) ) {
$result['upper'] += 1;
}
else if ( ctype_punct($c) ) {
$result['punct'] += 1;
}
else {
$result['others'] += 1;
}
}
return $result;
}
prints
array(5) {
["digit"]=>
int(8)
["lower"]=>
int(11)
["upper"]=>
int(14)
["punct"]=>
int(15)
["others"]=>
int(0)
}