RegExpr to insert space before \n - php

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

Related

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

Remove string after a certain character?

How can I remove the remaining part of a string after certain characters like ?, #, &, %, = in PHP? Any ideas? I tried preg_replace(), but I couldn't figure it out.
Update, just realized I read it wrong. You're looking for stuff before, not after. Updated code:
$test_string = 'remember?forget';
preg_match('/([^?#&%=]+)/', $test_string, $matches);
$part_before_char = $matches[1];
After run, $part_before_char = 'remember'
This should work:
$str = "Hello World#somesuffixstr";
preg_match("/^(.*?[?#&%=]).*/", $str, $str);
echo $str[1];
// Should output "Hello World#"
About the regex pattern:
It searches for beginning of string (^), then for any character 0 or more times (which is group #1), then such a symbol like & or %, then any character zero or more times. It replaces the string with the characters matched in group #1.
$str = 'mystring#deletedpartofstring';
$str = preg_replace('/[?#&%=].+/', '', $str);

How to add a space after a point?

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

php: delete word from sentence

i have the sentence
something about something WORD still something...
what is the most efficient metod to delete the word "WORD" from sentence in php?
thanks
You could replace it with nothing:
$sentence = str_replace('word', '', $sentence);
Although that would also ruin words like swordfish, turning them into sfish. So you could put spaces around the edges:
$sentence = str_replace(' word ', ' ', $sentence);
But then it won't match words at the end and beginning of sentences. So you might have to use a regex:
$sentence = preg_replace('/\bword\b/', '', $sentence);
The \b is a word boundary, which could be a space or a beginning of a string or anything like that.
Depends, str_replace might be what you're looking for. But note that it removes all occurrences.
Try this:
$fixed_string = str_replace(" WORD ", " ", $your_string);

Categories