How to add a space after a point? - php

I'd like to add a space after any point found with an alphabetic or numeric character just after it (no space found), assuming the next character after the point is not an end of line (cr, lf, ...) character.
preg_replace "/.[a-z0-9]{1}/" with "/. [a-z0-9]/i"
How may I do this in PHP ?

You can use a positive lookahead:
$str = preg_replace("/\.(?=[a-z\d])/i", ". ", $str);
DEMO

You already posted the almost correct answer
$text = preg_replace( '#\.([A-Za-z0-9])#', '. $1', $text );
should do the trick

Related

How to match alphanumeric and symbols using PHP?

I'm working with text content in UTF8 encoding stored in variable $title.
Using preg_replace, how do I append an extra space if the $title string is ending with:
upper/lower case character
digit
symbol, eg. ? or !
This should do the trick:
preg_replace('/^(.*[\w?!])$/', "$1 ", $string);
In essence what it does is if the string ends in one of your unwanted characters it appends a single space.
If the string doesn't match the pattern, then preg_replace() returns the original string - so you're still good.
If you need to expand your list of unwanted endings you can just add them into the character block [\w?!]
Using a positive lookbehind before the end of the line.
And replace with a space.
$title = preg_replace('/(?<=[A-Za-z0-9?!])$/',' ', $title);
Try it here
You may want to try this Pattern Matching below to see if that does it for you.
<?php
// THE REGEX BELOW MATCHES THE ENDING LOWER & UPPER-CASED CHARACTERS, DIGITS
// AND SYMBOLS LIKE "?" AND "!" AND EVEN A DOT "."
// HOWEVER YOU CAN IMPROVISE ON YOUR OWN
$rxPattern = "#([\!\?a-zA-Z0-9\.])$#";
$title = "What is your name?";
var_dump($title);
// AND HERE, YOU APPEND A SINGLE SPACE AFTER THE MATCHED STRING
$title = preg_replace($rxPattern, "$1 ", $title);
var_dump($title);
// THE FIRST var_dump($title) PRODUCES:
// 'What is your name?' (length=18)
// AND THE SECOND var_dump($title) PRODUCES
// 'What is your name? ' (length=19) <== NOTICE THE LENGTH FROM ADDED SPACE.
You may test it out HERE.
Cheers...
You need
$title=preg_replace("/.*[\w?!]$/", "\\0 ", $title);

PHP Regex: Remove words less than 3 characters

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.

Regex to insert dot (.) after characters, before new line

I'm reformatting some text, and sometimes I have a string, where there is a sentence which is not ended by a dot.
I'm running various checks for this purpose, and one more I'd like is to "Add dot after last character before new line".
I'm not sure how to form the regular expression for this:]
$string = preg_replace("/???/", ".\n", $string);
Try this one:
$string = preg_replace("/(?<![.])(?=[\n\r]|$)/", ".", $string);
negative lookbehind (?<![.]) is checking previous character is not .
positive lookahead (?=[\n\r]|$) is checking next character is a newline or end of string.
like this I suppose:
<?php
$string = "Add dot after last character before new line\n";
$string = preg_replace("/(.)$/", "$1.\n", $string);
print $string;
?>
This way the dot will be added after the word line in the sentence and before the \n.
demo : http://ideone.com/J4g7tH
I'd do:
$string = "Add dot after last character before new line\n";
$string = preg_replace("/([^.\r\n])$/s", "$1.", $string);
Thanks for all the answers, but none of them really caught all scenarios right.
I fumbled my way to a good solution using the word boundary regex character class:
// Add dot after every word boundary that is followed by a new line.
$string = preg_replace("/[\b][\n]/", ".\n", $string);
I guess [\b][\n] could just as well be \b\n without square brackets.
This works for me:
$content = preg_replace("/(\w+)(\n)/", "$1.$2", $content);
It will match a word immediately followed by a new line, and add a dot in between.
Will match:
Hello\n
Will not match:
Hello \n
or
Hello.\n

RegExpr to insert space before \n

I'm need to insert space before new-line-symbol if it's not yet. For ex, in the text like this:
Some text
need space dfgfgfkgkf
insert space between 'text' and 'need'..
$pattern = "/[^\s]\n/i";
$replace = " \n";
but this regexp don't work
Are you sure that your newline character is \n? I would go for a more general solution and use
echo preg_replace('/(?<=\S)(?=\r?\n)/',' ', $str);
I use a positive lookbehind and a positive lookahead assertion to find the position at the end of the row, therefor only a space as replacement is needed.
Try this:
$pattern = "/\n/";
$replace = " \n";
I tried the code below and it worked:
$str = "line1\nline2";
echo preg_replace('/\n/',' \n', $str);

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