preg_replace - only letters and replace spaces for plus character - php

I would like to accept in string PHP only letters and change all spaces for plus (+) character. Further I would like to accept only one plus next to each other. So this string:
$string = 'ex,a-mpl*e s++tri ng';
sholud replace for:
$string = 'example+s+tri+ng';
I tried like that:
#[^a-zA-Z0-9\+\]#
but that isn't helpful for me.
Can you help me? :)
EDIT:
aahh, and I would like to also accept only strings where string's lenth is 3 or more.

Try if something like this could be a good starting point:
$string = 'ex,a-mpl*e s++tri ng';
$pattern = array(
'/([^a-zA-Z\+\s])/',
'/(\+|\s)+/'
);
$replacement = array('', '+');
$result = preg_replace($pattern, $replacement, (strlen($string) > 3) ? $string : false);
var_dump($result); //<- return an empty string if the length is < 3

Just letters and digits
You got your regex already, just use it
$str = preg_replace('#[^a-zA-Z0-9\+\]#', '', $str);
Replace Spaces, strip multiple ones
$str = preg_replace('/\s+/', '+', $str);
How to solve such things
I don't want to be rude but the code I pasted, is just a slightly change of Example #4 from here http://us2.php.net/en/preg_replace
So please questions like this are very common and php.net really does a good job with putting examples together. So try to search there first!

Related

How can remove the numberic suffix in php?

For example, if I want to get rid of the repeating numeric suffix from the end of an expression like this:
some_text_here_1
Or like this:
some_text_here_1_5
and I want finally receive something like this:
some_text_here
What's the best and flexible solution?
$newString = preg_replace("/_?\d+$/","",$oldString);
It is using regex to match an optional underscore (_?) followed by one or more digits (\d+), but only if they are the last characters in the string ($) and replacing them with the empty string.
To capture unlimited _ numbers, just wrap the whole regex (except the $) in a capture group and put a + after it:
$newString = preg_replace("/(_?\d+)+$/","",$oldString);
If you only want to remove a numberic suffix if it is after an underscore (e.g. you want some_text_here14 to not be changed, but some_text_here_14 to be changed), then it should be:
$newString = preg_replace("/(_\d+)+$/","",$oldString);
Updated to fix more than one suffix
Strrpos is far better than regex on such a simple string problem.
$str = "some_text_here_13_15";
While(is_numeric(substr($str, strrpos($str, "_")+1))){
$str = substr($str,0 , strrpos($str, "_"));
}
Echo $str;
Strrpos finds the last "_" in str and if it's numeric remove it.
https://3v4l.org/OTdb9
Just to give you an idea of what I mean with regex not being a good solution on this here is the performance.
Regex:
https://3v4l.org/Tu8o2/perf#output
0.027 seconds for 100 runs.
My code with added numeric check:
https://3v4l.org/dkAqA/perf#output
0.003 seconds for 100 runs.
This new code performs even better than before oddly enough, regex is very slow. Trust me on that
You be the judge on what is best.
First you'll want to do a preg_replace() in order to remove all digits by using the regex /\d+/. Then you'll also want to trim any underscores from the right using rtrim(), providing _ as the second parameter.
I've combined the two in the following example:
$string = "some_text_here_1";
echo rtrim(preg_replace('/\d+/', '', $string), '_'); // some_text_here
I've also created an example of this at 3v4l here.
Hope this helps! :)
$reg = '#_\d+$#';
$replace = '';
echo preg_replace($reg, $replace, $string);
This would do
abc_def_ghi_123 > abc_def_ghi
abc_def_1 > abc_def
abc_def_ghi > abc_def_ghi
abd_def_ > abc_def_
abc_123_def > abd_123_def
in case of abd_def_123_345 > abc_def
one could change the line
$reg = '#(?:_\d+)+$#';

Remove empty space and plus sign from the beginning of a string

I have a string that begins with an empty space and a + sign :
$s = ' +This is a string[...]';
I can't figure out how to remove the first + sign using PHP. I've tried ltrim, preg_replace with several patterns and with trying to escape the + sign, I've also tried substr and str_replace. None of them is removing the plus sign at the beginning of the string. Either it doesn't replace it or it remplace/remove the totality of the string. Any help will be highly appreciated!
Edit : After further investigation, it seems that it's not really a plus sign, it looks 100% like a + sign but I think it's not. Any ideas for how to decode/convert it?
Edit 2 : There's one white space before the + sign. I'm using get_the_excerpt Wordpress function to get the string.
Edit 3 : After successfully removing the empty space and the + with substr($s, 2);, Here's what I get now :
$s == '#43;This is a string[...]'
Wiki : I had to remove 6 characters, I've tried substr($s, 6); and it's working well now. Thanks for your help guys.
ltrim has second parameter
$s = ltrim($s,'+');
edit:
if it is not working it means that there is sth else at the beginning of that string, eg. white spaces. You can check it by using var_dump($s); which shows you exactly what you have there.
You can use explode like this:
$result = explode('+', $s)[0];
What this function actually does is, it removes the delimeter you specify as a first argument and breaks the string into smaller strings whenever that delimeter is found and places those strings in an array.
It's mostly used with multiple ocurrences of a certain delimeter but it will work in your case too.
For example:
$string = "This,is,a,string";
$results = explode(',', $string);
var_dump($results); //prints ['This', 'is', 'a', 'string' ]
So in your case since the plus sign appears ony once the result is in the zero index of the returned array (that contains only one element, your string obviously)
Here's a couple of different ways I can think of
str_replace
$string = str_replace('+', '', $string);
preg_replace
$string = preg_replace('/^\+/', '', $string);
ltrim
$string = ltrim($string, '+');
substr
$string = substr($string, 1);
try this
<?php
$s = '+This is a string';
echo ltrim($s,'+');
?>
You can use ltrim() or substr().
For example :
$output = ltrim($string, '+');
or you can use
$output = substr($string, 1);
You can remove multiple characters with trim. Perhaps you were not re-assigning the outcome of your trim function.
<?php
$s = ' +This is a string[...]';
$s = ltrim($s, '+ ');
print $s;
Outputs:
This is a string[...]
ltrim in the above example removes all spaces and addition characters from the left hand side of the original string.

PHP trim and return a string from its right

I'm trying to take a string that's output from MySql like this (MySql outputs X characters):
$str = 'Buddy you're a boy make a big noise Playin in the stre';
and trying to start from the right side, trim whatever is there up till the first space. Sounded simple when I got down to it, but now, it has my brain and fingers in knots.
The output I'm tying to achieve is simple:
$str = 'Buddy you're a boy make a big noise Playin in the';
Notice, that characters starting from the right, till the first space, are removed.
Can you help?
My Fiddle
$str = 'Buddy you\'re a boy make a big noise Playin in the stre';
//echo rtrim($str,' ');
It's a useful idiom to remember on its own: to remove all the characters preceding a specific one from the right side of the string (including that special character), use the following:
$trimmed = substr($str, 0, strrpos($str, ' '));
... where ' ' is that special character.
Demo
If you don't know, however, whether or not the character is present, you'd check the result of sttrrpos first:
$last_space_index = strrpos($str, ' ');
$trimmed = $last_space_index !== false
? substr($str, 0, $last_space_index)
: $str;
And if there can be more than one character that you need to trim, like in 'hello there test' line, just rtrim the result:
$trimmed = rtrim(substr($str, 0, strrpos($str, ' ')), ' ');
In this case, however, a regex-based solution looks more appropriate:
$trimmed = preg_replace('/ +[^ ]*$/', '', $str);
I think your best option would be a regex replace:
preg_replace('/\s+\S*$/', '', $str);
which outputs Buddy you're a boy make a big noise Playin in the
And the Fiddle
it's probably easier to do it with regex, but I'm sooo bad with that! You shoud try this:
// Get all the words in an array
$strArray = explode(" ", $str);
// Remove the last word.
array_pop($strArray);
// Get it back into a sentence
$newString = implode(" ", $strArray);
There's a hundred ways to do this, here are some options:
array_pop'ing the last word off an array we create from explode:
$arr = explode(" ", $str);
$fixed_arr = array_pop($arr);
$result = implode(" ", $arr);
Using regular expressions:
$result = preg_replace('/\s+\S*$/', '', $str);
and using strrpos and substr:
$spacePos = strrpos($str, ' ');
$result = substr($str, 0, $spacePos);
In mysql use
left(field,length)
to output only the strlen first digits
right(field,length) having opposite effects
otherwise use substr($string,0,$length) or regex in php
As a matter of regex performance comparison, the regex engine can move faster through the string when it can perform greedy matching with minimal backtracking.
/ +[^ ]*$/ uses 68 steps. (#raina77ow)
/(?:[^ ]+\K )+.*/ uses 56 steps. (#mickmackusa)
/(?:\K [^ ]*)+/ uses 48 steps. (#mickmackusa)
\s+\S*$ uses 34 steps. (#ChrisBornhoft and #RyanKempt)
/.*\K .*/ uses just 15 steps. (#mickmackusa)
Based on these comparisons, I recommend greedily matching any characters, then restarting the fullstring match before matching the last occurring space, then matching zero or more characters until the end of the string.
Code: (Demo)
$string = "Buddy you're a boy make a big noise Playin in the stre";
var_export(
preg_replace('/.*\K .*/', '', $string)
);
Output:
'Buddy you\'re a boy make a big noise Playin in the'

regexp add space after comma but not when comma is thousands separator?

Using php regexp in a simple way, is it possible to modify a string to add a space after commas and periods that follow words but not after a comma or period that is preceded and followed by a number such as 1,000.00?
String,looks like this with an amount of 1,000.00
Needs to be changed to...
String, looks like this with an amount of 1,000.00
This should allow for multiple instances of course... Here is what I am using now but it is causing numbers to return as 1, 000. 00
$punctuation = ',.;:';
$string = preg_replace('/(['.$punctuation.'])[\s]*/', '\1 ', $string);
You could replace '/(?<!\d),|,(?!\d{3})/' with ', '.
Something like:
$str = preg_replace('/(?<!\d),|,(?!\d{3})/', ', ', $str);
I was searching for this regex.
This post really help me, and I improve solution proposed by Qtax.
Here is mine:
$ponctuations = array(','=>', ','\.'=>'. ',';'=>'; ',':'=>': ');
foreach($ponctuations as $ponctuation => $replace){
$string = preg_replace('/(?<!\d)'.$ponctuation.'(?!\s)|'.$ponctuation.'(?!(\d|\s))/', $replace, $string);
}
With this solution, "sentence like: this" will not be changed to "sentence like: this" (whith 2 blanck spaces)
That's all.
Although this is quite old, I was looking for this same question, and after understanding solutions given I have a different answer.
Instead of checking for character before the comma this regex checks the character after the comma and so it can be limited to alphabetic ones. Also this will not create a string with two spaces after a comma.
$punctuation = ',.;:';
$string = preg_replace("/([$punctuation])([a-z])/i",'\1 \2', $string);
Test script can be checked here.

Replace all characters in string apart from PHP

I have a string Trade Card Catalogue 1988 Edition I wish to remove everything apart from 1988.
I could have an array of all letters and do a str_replace and trim, but I wondered if this was a better solution?
$string = 'Trade Card Catalogue 1988 Edition';
$letters = array('a','b','c'....'x','y','z');
$string = str_to_lower($string);
$string = str_replace($letters, '', $string);
$string = trim($string);
Thanks in advance
Regular expression?
So assuming you want the number (and not the 4th word or something like that):
$str = preg_replace('#\D#', '', $str);
\D means every character that is not a digit. The same as [^0-9].
If there could be more numbers but you only want to get a four digit number (a year), this will also work (but obviously fails if you there are several four digit numbers and you want to get a specific one) :
$str = preg_replace('#.*?(\d{4,4}).*#', '\1', $str);
You can actually just pass the entire set of characters to be trimmed as a parameter to trim:
$string = trim($string, 'abc...zABC...Z ' /* don't forget the space */);

Categories