Add +1 to a string obtained from another site - php

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"

Related

How to filter propertly or how to explode specific string

Sorry to bother but I have tried now everything -.-
(INPUT STRING)
kronobergslan_Preem_AlmhultS_Esplanaden__diesel
this is the string, first value after _ is separate, second value after _ is separate, every other values except the last after __ is together as separate value.
so basically I want to make this:
(EXPECTED OUTPUT)
$a = kronobergslan
$b = Preem
$c = Almult S Esplanden
$d = diesel
Example 2:
(INPUT STRING)
kronobergslan_Circle_K_VaxjoSodra_Vallviksvagen_352_51_Vaxjo__diesel
(EXPECTED OUTPUT)
$a = kronobergslan
$b = Circle K
$c = Vaxjo Sodra Vallviksvagen 35251 Vaxjo
$d = diesel
I have tried everything.
public function filter($call){
// kronobergslan_Circle_K_VaxjoEvedalsvagen__diesel to Kronobergslan CircleK (Vaxjo Evedalsvagen)
// kronobergslan_Ingo_VaxjoSmedjegatan_28__Morners_vag__diesel to Kronobergslan Ingo (Vaxjo Smedjegatan 28 Morners vag)
// return array
$parts = explode("_", $call);
$parts = array_map('ucfirst', $parts);
// if part 2 and 3 is cirlek make one string
if($parts[1] == "Circle"){
$parts[1] = $parts[1] . " " . $parts[2];
unset($parts[3]);
}
$parts[10] = ucfirst(substr($call, strpos($call, "__") + 2));
//= $parts[count($parts) - 1];
if ($parts[2] != "K"){
$part = preg_split('/(?=[A-Z])/',$parts[2]);
$parts[2] = implode(' ', $part);
$parts[2] = $parts[2] . " " . $parts[3];
unset($parts[3]);
}else if ($parts[2] == "K"){
$parts[2] = "test";
}
return $parts;
}
Would be thankful if someone could explain how to approach this problem and how to solve it so I would learn from it and probably be able to solve it other times.
You're presented with a few problems with your expected input strings.
#kronobergslan_Preem_AlmhultS_Esplanaden__diesel
$parts = explode('_', $call);
#Outputs:
#kronobergslan
#Preem
#AlmhultS
#Esplanaden
#[empty entry]
#diesel
I would suggest, replace every space with another custom boundary, that way in the example of AlmhultS_Esplanaden you can still separate the input string with a simple explode and not have it be confused in these instances. Once separated, you can replace the _ with a \s.
I'm not sure why the last value has a double-underscore __ but since it's there, you can still use explode and then just remove the 2nd last value in the returned array using the unset method.
$parts = explode('_', $call);
$count = count($parts);
for ($i = 0; $i < $count; $i++) {
$parts[$i] = preg_replace('/','/\s/');
}
unset($parts[$count]-1);
As a side note, never use " unless you're concatenating a string. Always use ' single quotes.

How can I split a string into three word chunks?

I need to split a string in every three words using PHP
"This is an example of what I need."
The output would be:
This is an
is an example
an example of
example of what
of what I
what I need
I have this example with Java
String myString = "This is an example of what I need.";
String[] words = myString.split("\\s+");
for (int i = 0; i < words.length; i++) {
String threeWords;
if (i == words.length - 1)
threeWords = words[i];
else if(i == words.length - 2)
threeWords = words[i] + " " + words[i + 1];
else
threeWords = words[i] + " " + words[i + 1] + " " + words[i + 2];
System.out.println(threeWords);
}
Solution that use explode, array_slice and implode.
$example = 'This is an example of what I need.';
$arr = explode(" ",$example);
foreach($arr as $key => $word){
//if($key == 0) continue;
$subArr = array_slice($arr,$key,3);
if(count($subArr) < 3) break;
echo implode(" ",$subArr)."<br>\n";
}
Output:
This is an
is an example
an example of
example of what
of what I
what I need.
If you want to suppress the first output with This, remove the comment in the line
//if($key == 0) continue;
If the example can have less than 3 words and these should be output then the line with the break must be as follows:
if(count($subArr) < 3 AND $key != 0) break;
For strings that are not only separated by single spaces, preg_split is recommended. Example:
$example = "This is an example of what I need.
Sentence,containing a comma and Raphaël.";
$arr = preg_split('/[ .,;\r\n\t]+/u', $example, 0, PREG_SPLIT_NO_EMPTY);
foreach($arr as $key => $word){
$subArr = array_slice($arr,$key,3);
if(count($subArr) < 3) break;
echo implode(" ",$subArr)."<br>\n";
}
Output:
This is an
is an example
an example of
example of what
of what I
what I need
I need Sentence
need Sentence containing
Sentence containing a
containing a comma
a comma and
comma and Raphaël
To include only words (notice the fullstop is removed from the last trigram), use str_word_count() to form the array of strings.
Then you need to loop while there are three elements to print.
Code: (Demo)
$example = 'This is an example of what I need.';
$words = str_word_count($example, 1);
for ($x = 0; isset($words[$x + 2]); ++$x) {
printf("%s %s %s\n", $words[$x], $words[$x + 1], $words[$x + 2]);
}
Output:
This is an
is an example
an example of
example of what
of what I
what I need
If you don't like printf(), you could echo implode(' ', [the three elements]).
If you want to print a single string of words when there are less than 3 total words in the string, then you could use a post-test loop. Demo
And then, of course, if we going to stumble down the rocky road of "what is a word", then an ironclad definition of "what is a word" will need to be defined and then a regex (potentially with multibyte support) will need to be suitably crafted. Basic Demo

Want to iterate a string that after each charater there will be a space in PHP

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.

how to get last integer in a string?

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"
}

How to select start of a string until a :

I have this string:
467:some-text-here-1786
How can I select only the first numerical value before the ":" ?
Thank you
Very simple:
list($var) = explode(":",$input);
or
$tmp = explode(":",$input);
$var = array_shift($tmp);
or (as pointed out by PhpMyCoder)
$tmp = current(explode(":",$input));
$string = '467:some-text-here-1786';
$var = (int)$string;
Since you're extracting a number, this is enough :)
For an explanation of why this works, check the official PHP manual: http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion
It's also really fast and really safe: you are sure you get a number.
$a = "467:some-text-here-1786";
$a = explode(":", $a);
$a = $a[0];
another way to do this:
$length = strpos($string, ':') + 1;
$number = substr($string, 0, $length);

Categories