How can I insert symbol '+' after each char of a string?
Like changing from mystring to m+y+s+t+r+i+n+g+.
You can also use this:
print implode("+", str_split($string));
To add one extra + after, just concatenate . "+".
Note: this approach is fast enough for not very long strings. Another way is to use regular expressions as illustrated in #zerkms answer.
$str = 'string';
echo preg_replace('~.~', '\\0+', $str);
You can use preg_replace:
$text = 'mystring';
// To match only characters (no numbers):
$replaced = preg_replace("/([a-z])/i", "$1+", $text);
// To match both
$replaced = preg_replace("/([a-z0-9])/i", "$1+", $text);
Related
I have a string that has a number inside exactly one pair of quotes. How can I get this number using php?
I have tried iterating over the string and or using str_split but I'm not sure how to limit it to what is inside the quotation marks. The fact that the number can be any length makes it even harder.
EDIT: Here is an example
Hello this is my "100"th string!,
I would need to return 100;
echo intval('123string');
results in 123
preg_match() is a way to get the number from string. Example:
$str = 'Hello this is my "100"th string!,';
preg_match('/\d+/', $str, $match);
echo $match[0];
Demo
use preg_replace:
echo preg_replace("~[^\d+]~", '', 'Hello this is my "100"th string!,');
trim the quotes from around the string, and php will immediately see the number inside.
$str = "'1234'";
$num = trim($str, "'\"");
echo $num + 1;
// => 1235
or if you have text as well a string, replace all non-digits with spaces, then have
php automatically parse the string when it is used in an arithmetic expression.
$num = preg_replace('/\D/', ' ', $string) + 0;
I'm trying to remove all words of less than 3 characters from a string, specifically with RegEx.
The following doesn't work because it is looking for double spaces. I suppose I could convert all spaces to double spaces beforehand and then convert them back after, but that doesn't seem very efficient. Any ideas?
$text='an of and then some an ee halved or or whenever';
$text=preg_replace('# [a-z]{1,2} #',' ',' '.$text.' ');
echo trim($text);
Removing the Short Words
You can use this:
$replaced = preg_replace('~\b[a-z]{1,2}\b\~', '', $yourstring);
In the demo, see the substitutions at the bottom.
Explanation
\b is a word boundary that matches a position where one side is a letter, and the other side is not a letter (for instance a space character, or the beginning of the string)
[a-z]{1,2} matches one or two letters
\b another word boundary
Replace with the empty string.
Option 2: Also Remove Trailing Spaces
If you also want to remove the spaces after the words, we can add \s* at the end of the regex:
$replaced = preg_replace('~\b[a-z]{1,2}\b\s*~', '', $yourstring);
Reference
Word Boundaries
You can use the word boundary tag: \b:
Replace: \b[a-z]{1,2}\b with ''
Use this
preg_replace('/(\b.{1,2}\s)/','',$your_string);
As some solutions worked here, they had a problem with my language's "multichar characters", such as "ch". A simple explode and implode worked for me.
$maxWordLength = 3;
$string = "my super string";
$exploded = explode(" ", $string);
foreach($exploded as $key => $word) {
if(mb_strlen($word) < $maxWordLength) unset($exploded[$key]);
}
$string = implode(" ", $exploded);
echo $string;
// outputs "super string"
To me, it seems that this hack works fine with most PHP versions:
$string2 = preg_replace("/~\b[a-zA-Z0-9]{1,2}\b\~/i", "", trim($string1));
Where [a-zA-Z0-9] are the accepted Char/Number range.
I have a string that contains many underscores followed by words ex: "Field_4_txtbox" I need to find the last underscore in the string and remove everything following it(including the "_"), so it would return to me "Field_4" but I need this to work for different length ending strings. So I can't just trim a fixed length.
I know I can do an If statement that checks for certain endings like
if(strstr($key,'chkbox')) {
$string= rtrim($key, '_chkbox');
}
but I would like to do this in one go with a regex pattern, how can I accomplish this?
The matching regex would be:
/_[^_]*$/
Just replace that with '':
preg_replace( '/_[^_]*$/', '', your_string );
There is no need to use an extremly costly regex, a simple strrpos() would do the job:
$string=substr($key,0,strrpos($key,"_"));
strrpos — Find the position of the last occurrence of a substring in a string
You can also just use explode():
$string = 'Field_4_txtbox';
$temp = explode('_', strrev($string), 2);
$string = strrev($temp[1]);
echo $string;
As of PHP 5.4+
$string = 'Field_4_txtbox';
$string = strrev(explode('_', strrev($string), 2)[1]);
echo $string;
For example suppose I have
$blah = "C$###.a534&";
I wish to filter the string so that only letters, numbers and "." remain yielding "C.a534"
How do I do this?
If you know what characters should be allowed, you can use a negated character group (in a regular expression) to remove everything else:
$blah = preg_replace('/[^a-z0-9\.]/i', '', $blah);
Note that i am using the i modifier for the regular expression. It matches case-insensitive, so that we do not need to specify a-z and A-Z.
been answered lots of times but:
function cleanit($input){
return preg_replace('/[^a-zA-Z0-9.]/s', '', $input);
}
$blah = cleanit("C$###.a534&");
you can use preg_replace
$text = preg_replace('/[' . preg_quote('CHARSYOUDONTWANT','/') . ']/','',$text);
on other case for only chars you want try this,
$text = preg_replace('/[^' . preg_quote('CHARSONLYYOUWANT','/') . ']/','',$text);
for example
$blah = "C$###.a534&";
$blah = preg_replace('/[' . preg_quote('$##&','/') . ']/','',$blah);
echo $blah;
Or do it the other way round:
$text = preg_replace('/[^a-zA-Z0-9.]/','',$text);
http://php.net/manual/en/function.preg-replace.php
replace all non-valid characters with the empty string.
I have a text field in which user can enter any character he/she wants. But in server i have a string patter [a-z0-9][a-z0-9+.-]*, if any of the character in the value from the text box doesn't match the pattern, then i must remove that character from that string. How can i do that in php. is there any functions for that?
Thanks in advance.
Gowri Sankar
.. in PHP we use regular Expressions with preg_replace.
Here you have some help with examples...
http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/
this is what you need:
$new_text = preg_replace('#[^A-Za-z+.-0-9]#s','',$text);
Just use preg_replace with the allowed pattern negated.
For example, if you allow a to Z and spaces, you simply negate it by adding a ^ to the character class:
echo preg_replace('/[^a-z ]*/i', '', 'This is a String !!!');
The above would output: This is a String (without the exclamation marks).
So it's removing any character that is not a to Z or space, e.g. your pattern negated.
How about:
$string = 'A quick test &*(^&for you this should work';
$searchForThis = '/[^A-Za-z \s]/';
$replaceWithBlank = '';
echo preg_replace($searchForThis, $replaceWithBlank , $string);
Try this:
$strs = array('+abc123','+.+abc+123','abc&+123','#(&)');
foreach($strs as $str) {
$str = preg_replace('/(^[^a-z0-9]*)|([^a-z0-9+.-]*)/', '', $str);
echo "'",$str,"'\n";
}
Output:
'abc123'
'abc+123'
'abc+123'
''
str_replace('x','',$text);