preg_replace to capitalize a letter after a quote - php

I have names like this:
$str = 'JAMES "JIMMY" SMITH'
I run strtolower, then ucwords, which returns this:
$proper_str = 'James "jimmy" Smith'
I'd like to capitalize the second letter of words in which the first letter is a double quote. Here's the regexp. It appears strtoupper is not working - the regexp simply returns the unchanged original expression.
$proper_str = preg_replace('/"([a-z])/',strtoupper('$1'),$proper_str);
Any clues? Thanks!!

Probably the best way to do this is using preg_replace_callback():
$str = 'JAMES "JIMMY" SMITH';
echo preg_replace_callback('!\b[a-z]!', 'upper', strtolower($str));
function upper($matches) {
return strtoupper($matches[0]);
}
You can use the e (eval) flag on preg_replace() but I generally advise against it. Particularly when dealing with external input, it's potentially extremely dangerous.

Use preg_replace_callback - But you dont need to add an extra named function, rather use an anonymous function.
$str = 'JAMES "JIMMY" SMITH';
echo preg_replace_callback('/\b[a-z]/', function ($matches) {
return strtoupper($matches[0]);
}, strtolower($str));
Use of /e is be deprecated as of PHP 5.5 and doesn't work in PHP 7

Use the e modifier to have the substitution be evaluated:
preg_replace('/"[a-z]/e', 'strtoupper("$0")', $proper_str)
Where $0 contains the match of the whole pattern, so " and the lowercase letter. But that doesn’t matter since the " doesn’t change when send through strtoupper.

A complete solution doesn't get simpler / easier to read than this...
Code: https://3v4l.org/rrXP7
$str = 'JAMES "JIMMY" SMITH';
echo ucwords(strtolower($str), ' "');
Output:
James "Jimmy" Smith
It is merely a matter of declaring double quotes and spaces as delimiters in the ucwords() call.
Nope. My earlier self was not correct. It doesn't get simpler than this multibyte-safe title-casing technique!
Code: (Demo)
echo mb_convert_case($str, MB_CASE_TITLE);
Output:
James "Jimmy" Smith

I do this without regex, as part of my custom ucwords() function. Assuming no more than two quotes appear in the string:
$parts = explode('"', $string, 3);
if(isset($parts[2])) $string = $parts[0].'"'.ucfirst($parts[1]).'"'.ucfirst($parts[2]);
else if(isset($parts[1])) $string = $parts[0].'"'.ucfirst($parts[1]);

You should do this :
$proper_str =
preg_replace_callback(
'/"([a-z])/',
function($m){return strtoupper($m[1]);},
$proper_str
);
You should'nt use "eval()" for security reasons.
Anyway, the patern modifier "e" is deprecated.
See : PHP Documentation.

echo ucwords(mb_strtolower('JAMES "JIMMY" SMITH', 'UTF-8'), ' "'); // James "Jimmy" Smith
ucwords() has a second delimiter parameter, the optional delimiters contains the word separator characters. Use space ' ' and " as delimiter there and "Jimmy" will be correctly recognized.

Related

How to add single quote with Regex php arrays

For From
$data[ContactInfos][ContactInfo][Addresses]
to
$data['ContactInfos']['ContactInfo']['Addresses']
Try the following regex(Demo):
(?<=\[)|(?=\])
PHP(Demo):
preg_replace('/(?<=\[)|(?=\])/', "'", $str);
With this
preg_replace('/\[([^\]]+)\]/', "['\1']", $input);
Try it here
https://regex101.com/r/YTIOWY/1
If you have mixed string - with and without quote, regex must be a little sophysticated
$str = '$data[\'ContactInfos\'][ContactInfo]["Addresses"]';
$str = preg_replace('/(?<=\[)(?!(\'|\"))|(?<!(\'|\"))(?=\])/', "'", $str);
// result = $data['ContactInfos']['ContactInfo']["Addresses"]
demo
The first rule of regex: "Don't use regex unless you have to."
This question doesn't require regex and the function call is not prohibitively convoluted. Search for square brackets, and write a single quote on their "inner" side.
Code (Demo)
$string='$data[ContactInfos][ContactInfo][Addresses]';
echo str_replace(['[',']'],["['","']"],$string);
Output:
$data['ContactInfos']['ContactInfo']['Addresses']

replace elements in string PHP

I have a string "Hello World !" and I want to replace some letters in it and receive result like "He!!! W!r!d !" it's means that i changed all "l" and "o" to "!"
I found function preg_replace();
function replace($s){
return preg_replace('/i/', '!', "$s");
}
and it works with exactly one letter or symbol, and I want to change 2 symbols to "!".
Change your function as such;
function replace($s) {
return preg_replace('/[ol]/', '!', $s);
}
Read more on regular expressions here to get further understanding on how to use regular expressions.
Since you are already using regular expressions, why not really use then to work with the pattern you are really looking for?
preg_replace('/l+/', '!', "Hello"); // "He!o" ,so rewrites multiple occurances
If you want exactly two occurances:
preg_replace('/l{2}/', '!', "Helllo"); // "He!lo" ,so rewrites exactly two occurances
Or what about that:
preg_replace('/[lo]/', '!', "Hello"); // "He!!!" ,so rewrites a set of characters
Play around a little using an online tool for such: https://regex101.com/
This can be accomplished either using preg_replace() like you're trying to do or with str_replace()
Using preg_replace(), you need to make use of the | (OR) meta-character
function replace($s){
return preg_replace('/l|o/', '!', "$s");
}
To do it with str_replace() you pass all the letters that you want to replace in an array, and then the single replacing character as just a string (or, if you want to use multiple replacing characters, then also pass an array).
str_replace(array("l","o"), "!", $s);
Live Example
Using preg_replace like you did:
$s = 'Hello World';
echo preg_replace('/[lo]/', '!', $s);
I think another way to do it would be to use an array and str_replace:
$s = 'Hello World';
$to_replace = array('o', 'l');
echo str_replace($to_replace, '!', $s);

How to extract a collection of numbers from a string?

I need to extract a project number out of a string. If the project number was fixed it would have been easy, however it can be either P.XXXXX, P XXXXX or PXXXXX.
Is there a simple function like preg_match that I could use? If so, what would my regular expression be?
There is indeed - if this is part of a larger string e.g. "The project (P.12345) is nearly done", you can use:
preg_match('/P[. ]?(\d{5})/',$str,$match);
$pnumber = $match[1];
Otherwise, if the string will always just be the P.12345 string, you can use:
preg_match('/\d{5}$/',$str,$match);
$pnumber = $match[0];
Though you may prefer the more explicit match of the top example.
Try this:
if (preg_match('#P[. ]?(\d{5})#', $project_number, $matches) {
$project_version = $matches[1];
}
Debuggex Demo
You said that project number is 4 of 5 digit length, so:
preg_match('/P[. ]?(\d{4,5})/', $tring, $m);
$project_number = $m[1];
Assuming you want to extract the XXXXX from the string and XXXXX are all integers, you can use the following.
preg_replace("/[^0-9]/", "", $string);
You can use the ^ or caret character inside square brackets to negate the expression. So in this instance it will replace anything that isn't a number with nothing.
I would use this kind of regex : /.*P[ .]?(\d+).*/
Here is a few test lines :
$string = 'This is the P123 project, with another useless number 456.';
$project = preg_replace('/.*P[ .]?(\d+).*/', '$1', $string);
var_dump($project);
$string = 'This is the P.123 project, with another useless number 456.';
$project = preg_replace('/.*P[ .]?(\d+).*/', '$1', $string);
var_dump($project);
$string = 'This is the P 123 project, with another useless number 456.';
$project = preg_replace('/.*P[ .]?(\d+).*/', '$1', $string);
var_dump($project);
use explode() function to split those

PHP trim entire words

How to trim entire words from php string
like I dont want "foo", "bar", "mouse" words on left and "killed" on the end of string.
So "fo awesome illed" would not be trimmed
But "foo awesome killed" => " awesome "
"killed awesome foo" not trimmed (killed trimmed from right, rest from left)
When I'm using ltrim($str, "foo"); it will trim any letter from "foo" - "f" or "o"
Use preg_replace() to replace the strings with an empty string.
$str = preg_replace('/^(foo|bar|mouse)|killed$/', '', $str);
Go to regular-expressions.info to learn more about regexp.
str_replace($replaceme, $withme, $here) works much faster (and is easier) if you dont need advanced regex features.
If you know the exact word you are looking for ($replaceme) and you want to delete it you can just use "" (empty string) in the $withme parameter.
Use preg_match function and create your own patteren based on your requirment.
<?php
$subject = "abcdef";
$pattern = '/^foo$killed/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
?>

Remove unallowed character from specific pattern in the php

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);

Categories