CSS or PHP add space in number format - php

How can I add a space after 3 and 4 digits ?
I have this numbers: +4420719480
The result needs to be: +44 2071 9480
How can I add the spaces with css or php after 4 characters?
I have tried the following code:
$str = "+4420719480";
echo chunk_split($str, 4, ' ');
But how do I add the space to the first 3 characters and then to the 4th?

You can use preg_replace
$str = '+4420719480';
echo preg_replace('~^.{3}|.{4}(?!$)~', '$0 ', $str);
pattern explanation:
~ # pattern delimiter
^.{3} # any character 3 times at the start of the string
| # OR
.{4} # any character 4 times
(?!$) # not followed by the end of the string
~ # pattern delimiter
replacement: '$0 ' (the whole pattern and a space)

Sometimes the most mundane solution will do the job just fine.
$str = "+4420719480";
$new = substr($str,0,3).' '.substr($str,3,4).' '.substr($str,7);

Using your code, you can do:
$str = "+4420719480";
echo strrev(chunk_split(strrev($str),4," "));
Kinda clunky and only works for this size of $str, but it works!

Related

Php make spaces in a word with a dash

I have the following string:
$thetextstring = "jjfnj 948"
At the end I want to have:
echo $thetextstring; // should print jjf-nj948
So basically what am trying to do is to join the separated string then separate the first 3 letters with a -.
So far I have
$string = trim(preg_replace('/s+/', ' ', $thetextstring));
$result = explode(" ", $thetextstring);
$newstring = implode('', $result);
print_r($newstring);
I have been able to join the words, but how do I add the separator after the first 3 letters?
Use a regex with preg_replace function, this would be a one-liner:
^.{3}\K([^\s]*) *
Breakdown:
^ # Assert start of string
.{3} # Match 3 characters
\K # Reset match
([^\s]*) * # Capture everything up to space character(s) then try to match them
PHP code:
echo preg_replace('~^.{3}\K([^\s]*) *~', '-$1', 'jjfnj 948');
PHP live demo
Without knowing more about how your strings can vary, this is working solution for your task:
Pattern:
~([a-z]{2}) ~ // 2 letters (contained in capture group1) followed by a space
Replace:
-$1
Demo Link
Code: (Demo)
$thetextstring = "jjfnj 948";
echo preg_replace('~([a-z]{2}) ~','-$1',$thetextstring);
Output:
jjf-nj948
Note this pattern can easily be expanded to include characters beyond lowercase letters that precede the space. ~(\S{2}) ~
You can use str_replace to remove the unwanted space:
$newString = str_replace(' ', '', $thetextstring);
$newString:
jjfnj948
And then preg_replace to put in the dash:
$final = preg_replace('/^([a-z]{3})/', '\1-', $newString);
The meaning of this regex instruction is:
from the beginning of the line: ^
capture three a-z characters: ([a-z]{3})
replace this match with itself followed by a dash: \1-
$final:
jjf-nj948
$thetextstring = "jjfnj 948";
// replace all spaces with nothing
$thetextstring = str_replace(" ", "", $thetextstring);
// insert a dash after the third character
$thetextstring = substr_replace($thetextstring, "-", 3, 0);
echo $thetextstring;
This gives the requested jjf-nj948
You proceeding is correct. For the last step, which consists in inserting a - after the third character, you can use the substr_replace function as follows:
$thetextstring = 'jjfnj 948';
$string = trim(preg_replace('/\s+/', ' ', $thetextstring));
$result = explode(' ', $thetextstring);
$newstring = substr_replace(implode('', $result), '-', 3, false);
If you are confident enough that your string will always have the same format (characters followed by a whitespace followed by numbers), you can also reduce your computations and simplify your code as follows:
$thetextstring = 'jjfnj 948';
$newstring = substr_replace(str_replace(' ', '', $thetextstring), '-', 3, false);
Visit this link for a working demo.
Oldschool without regex
$test = "jjfnj 948";
$test = str_replace(" ", "", $test); // strip all spaces from string
echo substr($test, 0, 3)."-".substr($test, 3); // isolate first three chars, add hyphen, and concat all characters after the first three

Regex in PHP: Replacing text between strings

Okay I have made some progress on a problem I am solving, but need some help with a small glitch.
I need to remove all characters from the filenames in the specific path images/prices/ BEFORE the first digit, except for where there is from_, in which case remove all characters from the filename BEFORE from_.
Examples:
BEFORE AFTER
images/prices/abcde40.gif > images/prices/40.gif
images/prices/UgfVe5559.gif > images/prices/5559.gif
images/prices/wedsxcdfrom_88457.gif > images/prices/from_88457.gif
What I've done:
$pattern = '%images/(.+?)/([^0-9]+?)(from_|)([0-9]+?)\.gif%';
$replace = 'images/\\1/\\3\\4.gif';
$string = "AAA images/prices/abcde40.gif BBB images/prices/wedsxcdfrom_88457.gif CCC images/prices/UgfVe5559.gif DDD";
$newstring = str_ireplace('from_','733694521548',$string);
while(preg_match($pattern,$newstring)){
$newstring=preg_replace($pattern,$replace,$newstring);
}
$newstring=str_ireplace('733694521548','from_',$newstring);
echo "Original:\n$string\n\nNew:\n$newstring";
My expected output is:
AAA images/prices/40.gif BBB images/prices/from_88457.gif CCC images/prices/5559.gif DDD"
But instead I am getting:
AAA images/prices/40.gif BBB images/from_88457.gif CCC images/5559.gif DDD
The prices/ part of the path is missing from the last two paths.
Note that the AAA, BBB etc. portions are just placeholders. In reality the paths are scattered all across a raw HTML file parsed into a string, so we cannot rely on any pattern in between occurrences of the text to be replaced.
Also, I know the method I am using of substituting from_ is hacky, but this is purely for a local file operation and not for a production server, so I am okay with it. However if there is a better way, I am all ears!
Thanks for any assistance.
You can use lookaround assertions:
preg_replace('~(?<=/)(?:([a-z]+)(?=\d+\.gif)|(\w+)(?=from_))~i', '', $value);
Explanation:
(?<=/) # If preceded by a '/':
(?: # Begin group
([a-z]+) # Match alphabets from a-z, one or more times
(?=\d+\.gif) # If followed followed by digit(s) and '.gif'
| # OR
(\w+) # Match word characters, one or more times
(?=from_) # If followed by 'from_'
) # End group
Visualization:
Code:
$pattern = '~(?<=/)(?:([a-z]+)(?=\d+\.gif)|(\w+)(?=from_))~i';
echo preg_replace($pattern, '', $string);
Demo
You can use this regex for replacement:
^(images/prices/)\D*?(from_)?(\d+\..+)$
And use this expression for replacement:
$1$2$3
RegEx Demo
Code:
$re = '~^(images/prices/)\D*?(from_)?(\d+\..+)$~m';
$str = "images/prices/abcde40.gif\nimages/prices/UgfVe5559.gif\nimages/prices/wedsxcdfrom_88457.gif";
$result = preg_replace($re, '$1$2$3', $str);
You can try with Lookaround as well. Just replace with blank string.
(?<=^images\/prices\/).*?(?=(from_)?\d+\.gif$)
regex101 demo
Sample code: (directly from above site)
$re = "/(?<=^images\\/prices\\/).*?(?=(from_)?\\d+\\.gif$)/m";
$str = "images/prices/abcde40.gif\nimages/prices/UgfVe5559.gif\nimages/prices/wedsxcdfrom_88457.gif";
$subst = '';
$result = preg_replace($re, $subst, $str);
If string is not multi-line then use \b as word boundary instead of ^ and $ to match start and end of the line/string.
(?<=\bimages\/prices\/).*?(?=(from_)?\d+\.gif\b)
$arr = array(
'images/prices/abcde40.gif',
'images/prices/UgfVe5559.gif',
'images/prices/wedsxcdfrom_88457.gif'
);
foreach($arr as $str){
echo preg_replace('#images/prices/.*?((from_|\d).*)#i','images/prices/$1',$str);
}
DEMO
EDIT:
$str = 'AAA images/prices/abcde40.gif BBB images/prices/wedsxcdfrom_88457.gif CCC images/prices/UgfVe5559.gif DDD';
echo preg_replace('#images/prices/.*?((from_|\d).*?\s|$)#i','images/prices/$1',$str), PHP_EOL;

Regex extracting characters between last and second last occurance of character

i am trying to extract the word in between the last / and the second last / - i.e. food in the following PHP example.
$string = https://ss1.xxx/img/categories_v2/FOOD/fastfood (would like to replace $string to food)
$string = https://ss1.xxx/img/categories_v2/SHOPS/barbershop (would like to replace $string to shops)
I am new to regex and tried /[^/]*$ - however that is returning everying after the last /.. any help would be appreciated.. thanks!
I am using PHP.
Use:
preg_match('#/([^/]*)/[^/]*$#', $string, $match);
echo $match[1];
You could also use:
$words = explode('/', $string);
echo $words[count($words)-2];
You can use this:
$result = preg_replace_callback('~(?<=/)[^/]+(?=/[^/]*$)~', function ($m) {
return strtolower($m[0]); }, $string);
Pattern details:
~ # pattern delimiter
(?<=/) # zero width assertion (lookbehind): preceded by /
[^/]+ # all characters except / one or more times
(?=/[^/]*$) # zero width assertion (lookahead): followed by /,
# all that is not a / zero or more times, and the end of the string
~ # pattern delimiter
Regex:
(\w+)(/[^/]+)$
PHP code:
<?php
$string = "https://ss1.xxx/img/categories_v2/FOOD/fastfood";
echo preg_replace("#(\w+)(/[^/]+)$#", "food$2", $string);
$string = "https://ss1.xxx/img/categories_v2/SHOPS/barbershop";
echo preg_replace("#(\w+)(/[^/]+)$#", "shops$2", $string);
?>

preg_replace clips characters in string

i have a string (part of a JSON data) and want to parse it in brackets [...]. here is the example :
For example
[-0.5937, 2.0734,-0.1577, 1.7941,0.2048, 1.5296] >>> [-0.5937, 2.0734], [-0.1577, 1.7941], [0.2048, 1.5296]
i wrote this PHP code works good but the problem is: when it finds the ',' and adding '], [' characters instead of it, deletes the some digits of coordinates. You can check it by adding 123456789 value after the coordinates. for example -0.5937 => -0.5937123456789 So how can i avoid deleting digits of coordinates ???
Example Code
<?php
$line = '[-0.5937, 2.0734,-0.1577, 1.7941,0.2048, 1.5296]';
$brackets = preg_replace('/\d,\S/', '], [', $line);
echo $brackets;
?>
You can do this:
$string = '[-0.5937, 2.0734,-0.1577, 1.7941,0.2048, 1.5296]';
$pattern = '~[[,]\s*(-?\d++(?>\.\d++)?)\s*,\s*(-?\d++(?>\.\d++)?)\s*(?:]|(?=(,)))~';
$result = preg_replace($pattern, '[$1, $2]$3 ', $string);
pattern details:
~ # pattern delimiter
[[,] # a [ or a ,
\s* # optional spaces
(-?\d++(?>\.\d++)?) # a number (group 1)
\s*,\s* # ,
(-?\d++(?>\.\d++)?) # (group 2)
\s*
(?: # non capturing group
] # literal ]
| # OR
(?=(,)) # a lookahead that capture the comma (group 3)
)
~
You can do this using an assertion to prevent the pattern from capturing the digit and the non-whitespace character. like so:
'/(?<=\d),(?<=\S)/'
Or, you can just change your pattern to:
'/,(?<=\S)/'
to ignore the digit character.
What I would recommend doing, however, would make your code not rely on the space before numbers. Use preg_replace_callback:
<?php
$line = '[-0.5937, 2.0734,-0.1577, 1.7941,0.2048, 1.5296]';
$i = 0;
function everyOther($matches) {
$i++;
if ($i % 2 == 1)
return ',';
else
return '], [';
}
$brackets = preg_replace_callback(
'/,/',
'everyOther',
$line);
echo $brackets;
?>
This will replace every other comma.

How to remove all punctuation in a string just get the words separated by spaces in PHP

I want to remove any type of special characters in a string like this:
This is, ,,, *&% a ::; demo + String. +
Need to**#!/// format:::::
!!! this.`
Output Required:
This is a demo String Need to format this
How to do this using REGEX?
Check for any repeated instance of a non-number, non-letter character and repeat with a space:
# string(41) "This is a demo String Need to format this"
$str = trim( preg_replace( "/[^0-9a-z]+/i", " ", $str ) );
Demo: http://codepad.org/hXu6skTc
/ # Denotes start of pattern
[ # Denotes start of character class
^ # Not, or negative
0-9 # Numbers 0 through 9 (Or, "Not a number" because of ^
a-z # Letters a through z (Or, "Not a letter or number" because of ^0-9
] # Denotes end of character class
+ # Matches 1 or more instances of the character class match
/ # Denotes end of pattern
i # Case-insensitive, a-z also means A-Z
Use:
preg_replace('#[^a-zA-Z0-9 ]#', '', $yourString);
If characters are not alphabet, numbers or space, it is replaced with empty string.
Example:
$yourString = 'This is, ,,, *&% a ::; demo + String. + Need to**#!/// format::::: !!! this.`';
$newStr = preg_replace('#[^a-zA-Z0-9 ]#', '', $yourString);
echo $newStr;
Result:
This is a demo String Need to format this
So you can allow more characters if you want by putting them in:
[^a-zA-Z0-9 ]
Note: Also if you don't want to allow multiple spaces between words (though they wont be shown when output in browser), you need to use this instead:
preg_replace('#[^a-zA-Z0-9]+#', ' ', $yourString);
echo preg_replace('/[^a-z]+/i', ' ', $str);
// This is a demo String Need to format this
$string = preg_replace('/[^a-z]+/i', ' ', $string);
You may also want to allow ' in your character class to have conjunctions like don't not be turned into don t:
$string = preg_replace('/[^a-z\']+/i', ' ', $string);
You might also want to trim it afterwards to remove leading and trailing whitespace:
$string = trim(preg_replace('/[^a-z\']+/i', ' ', $string));

Categories