Regular expressins in php - php

I need a regular expression to check a string for uppercase letters. Where It finds a uppercase It needs to add white space before it. I write some code for this, but the problem is that it only works if there is only one uppercase letter in the string. But I need to work with any number of uppercase letter exists in the string. I pasted my code below:
$regEx = preg_match('*[A-Z]*', $str, $matches, PREG_OFFSET_CAPTURE);
if(!empty($regEx)) {
$str = substr_replace($str,' ', $matches[0][1], 0);
}

I need a regular expression to check a string for uppercase letters. Where it finds a uppercase, it needs to add white space before it.
preg_replace() sounds a more suitable candidate to achieve this...
$str = preg_replace('/[A-Z]/', ' $0', $str);
CodePad.

Please try below code:
if(preg_match("/[A-Z]/", $string)===0) {
return true;
}

Related

How to change specific first Letter in string to Capital using PHP?

If the first character of my string contains any of the following letters, then I would like to change the first letter to Uppercase: (a,b,c,d,f,g,h,j,k,l,m,n,o,p,q,r,s,t,v,w,y,z) but not (e,i,u,x).
For example,
luke would become Luke
egg would stay the same as egg
dragon would become Dragon
I am trying to acheive this with PHP, here's what I have so far:
<?php if($str("t","t"))
echo ucfirst($str);
else
echo "False";
?>
My code is simply wrong and it doesn't work and I would be really grateful for some help.
Without regex:
function ucfirstWithCond($str){
$exclude = array('e','i','u','x');
if(!in_array(substr($str, 0, 1), $exclude)){
return ucfirst($str);
}
return $str;
}
$test = "egg";
var_dump(ucfirstWithCond($test)); //egg
$test = "luke";
var_dump(ucfirstWithCond($test)); //Luke
Demo:
http://sandbox.onlinephpfunctions.com/code/c87c6cbf8c616dd76fe69b8f081a1fbf61cf2148
You may use
$str = preg_replace_callback('~^(?![eiux])[a-z]~', function($m) {
return ucfirst($m[0]);
}, $str);
See the PHP demo
The ^(?![eiux])[a-z] regex matches any lowercase ASCII char at the start of the string but e, u, i and x and the letter matched is turned to upper inside the callback function to preg_replace_callback.
If you plan to process each word in a string you need to replace ^ with \b, or - to support hyphenated words - with \b(?<!-) or even with (?<!\S) (to require a space or start of string before the word).
If the first character could be other than a letter then check with an array range from a-z that excludes e,i,u,x:
if(in_array($str[0], array_diff(range('a','z'), ['e','i','u','x']))) {
$str[0] = ucfirst($str[0]);
}
Probably simpler to just check for the excluded characters:
if(!in_array($str[0], ['e','i','u','x'])) {
$str[0] = ucfirst($str[0]);
}

PHP preg_replace help trim special characters

I tried to search around but couldn't find anything useful. I need to trim special characters from beginning and end of a string and identify if the remaining portion is a number.
For example
(5)
[[12]]
{3}
#!8(#
!255=
/879/
I need a preg_match expression for it. The regular expression should ignore the string if any alphabets come in between.
$string="yourstring";
$new_string=preg_replace('/[^A-Za-z0-9]/', '', $string);
if(is_numeric($new_string){
echo "number";
} else {
echo "string";
}
^(?!.*[a-zA-Z])\W*(\d+)\W*$
You can use this.Lookahead will validate if only numbers are there.Replace by $1.See demo.
https://regex101.com/r/cT0hV4/2

How do I replace all uppercase letters with a dash and lowercase with regex?

How does one replace all uppercase letters with a dash and lowercase equivalent in php?
Such as understandRegexBetter to understand-regex-better?
My Google-fu and experimentation with the following code hasn't gotten me very far.
echo preg_replace('/[A-Z]+/', "-$'", "understandRegexBetter");
Edit:
I forgot to specifically state that the first character is never uppercase.
Preferred Method:
This method replaces any set of capital letters preceded by a lowercase letter with a - and the set of capital letters. Then we lowercase the whole string after the fact.
echo strtolower(preg_replace(
'/(?<=[a-z])([A-Z]+)/',
'-$1',
'understandRegexBetter'
));
RegEx Callback:
Uses preg_replace_callback() to replace any set of capital letters with a - followed by the letters passed through strtolower(). This, however, will leave a preceding - in your string (we could look for a preceding characters in the RegEx, but then your first letter would be left uppercase).
echo preg_replace_callback(
'/[A-Z]+/',
function ($matches) {
$character = reset($matches);
return '-' . strtolower($character);
},
'understandRegexBetter'
);
Deprecated:
Side note, you can technically use preg_replace() with the e modifier but it is deprecated as of PHP 5.5. An example would be:
echo preg_replace(
'/([A-Z]+)/e',
'"-" . strtolower("$1")',
'understandRegexBetter'
);
You can do this:
echo strtolower(preg_replace('~(?=[A-Z])(?!\A)~', '-', $str));
try this:
echo strtolower(preg_replace('/([A-Z]+)/', "-$1", "understandRegexBetter"));
You can use:
$s = 'understandRegexBetter';
$r = preg_replace_callback('~(?<=[a-z])([A-Z])~',
function ($m) { return '-' . strtolower($m[1]); }, $s);
echo $r;
You could try something like this (e flag means evaluate):
echo preg_replace('/([A-Z])/e', "strtolower('-\\1')", "understandRegexBetter");

preg_replace() pattern to remove brackets and content in php

I want to remove the brackets with its content using preg_replace(), but i am unable to use a lazy(non-greedy) in the pattern since the end bracket is the end character, the text in between the brackets is always a random character length and can contain numbers, underscores, and hyphens.
code-
$array = array(
"Text i want to keep (txt to remove)",
"Random txt (some more random txt)",
"Keep this (remove)",
"I like bananas (txt)"
);
$pattern = "#pattern#";
foreach($array as $new_txt){
$new_outputs .= preg_replace($pattern, '', $new_txt)."\n";
}
echo $new_outputs;
Wanted output-
Text i want to keep
Random txt
Keep this
I like bananas
I do not use regular expressions much and couldn't find anything to solve my problem.
The following regular expression should do it:
$pattern = '#\(.*?\)#';
.*? is a non-greedy match of anything.
$new_outputs .= preg_replace('#\([^\)]*\)$#','',$new_txt);
This might help you:
$pattern = "/\([^)]*\)+/";
foreach($array as $new_txt){
$new_outputs .= preg_replace($pattern, '', $new_txt)."\n";
}

Masking all but first letter of a word using Regex

I'm attempting to create a bad word filter in PHP that will analyze the word and match against an array of known bad words, but keep the first letter of the word and replace the rest with asterisks. Example:
fook would become f***
shoot would become s**
The only part I don't know is how to keep the first letter in the string, and how to replace the remaining letters with something else while keeping the same string length.
$string = preg_replace("/\b(". $word .")\b/i", "***", $string);
Thanks!
$string = 'fook would become';
$word = 'fook';
$string = preg_replace("~\b". preg_quote($word, '~') ."\b~i", $word[0] . str_repeat('*', strlen($word) - 1), $string);
var_dump($string);
$string = preg_replace("/\b".$word[0].'('.substr($word, 1).")\b/i", "***", $string);
This can be done in many ways, with very weird auto-generated regexps...
But I believe using preg_replace_callback() would end up being more robust
<?php
# as already pointed out, your words *may* need sanitization
foreach($words as $k=>$v)
$words[$k]=preg_quote($v,'/');
# and to be collapsed into a **big regexpy goodness**
$words=implode('|',$words);
# after that, a single preg_replace_callback() would do
$string = preg_replace_callback('/\b('. $words .')\b/i', "my_beloved_callback", $string);
function my_beloved_callback($m)
{
$len=strlen($m[1])-1;
return $m[1][0].str_repeat('*',$len);
}
Here is unicode-friendly regular expression for PHP:
function lowercase_except_first_letter($s) {
// the following line SKIP the first word and pass it to callback func...
// \W it allows to keep the first letter even in words in quotes and brackets
return preg_replace_callback('/(?<!^|\s|\W)(\w)/u', function($m) {
return mb_strtolower($m[1]);
}, $s);
}

Categories