Replace all characters except first one and whitespaces - php

Hi
I trying do something like that:
I've got some string - 'Hello World!' for example.
And I want replace all character in it except the first one and white spaces.
so... result will be: "H.... ......";
I don't want delete it, just replacing with "." or other character.
I tried doing this with preg_replace but with no results.

You can do it like so:
$hidden = preg_replace('/(?!^)\S/', '.', $text);
It works by ensuring that we aren't at the beginning of the string with a negative lookahead for the start of string anchor, then matches a non-whitespace character using the negated whitespace character class.

preg_replace('/(?<!^)\S/', '.', $s)

Related

How to replace all occurrences of \ only if they are not followed by n?

Seems to be relatively simple task that gets me stuck in one PHP application. I have a string which has a bunch of \n in it. Those are fine and need to stay there. However, there are also single occurrences of the character \ and those I need to replace or remove, let's just say with empty character without removing the ones that are followed by n.
The best I came up with was to first replace all \n with something else, some weird character, then replace the remaining \ with empty space and then convert back the weird character to \n. However, that seems to be a waste of time and resources, besides, nothing guarantees me that I'll find weird enough character that will never be encountered in the rest of the string...
Any tips?
You need
$s = preg_replace('~\\\\(?!n)~', '', $s);
See the PHP demo:
$s = '\\n \\t \\';
$s = preg_replace('~\\\\(?!n)~', '', $s);
echo $s; // => \n t
We need 4 backslashes to pass 2 literal backslashes to the regex engine to match 1 literal backslash in the input string. The (?!n) is a negative lookahead that fails all matches of a backslash that is immediately followed with n.
You should be able to do this with a negative lookahead assertion:
\\(?!n)
The \\ looks for the backslash, the (?!n) asserts that the next character is not an n, but does not match the character.
To use this in PHP:
$text = 'foo\nbar\nb\az\n';
$newtext = preg_replace('/\\\\(?!n)/', '', $text);
Details here: https://regex101.com/r/F2qhAP/1

Remove more than two returns and more than one space within php string

I manage to remove the spaces but I can't understand why it would remove my returns as well. I have a textarea in my form and I want to allow up to two returns maximum. Here is what I have been using so far.
$string = preg_replace('/\s\s+/', ' ', $string); // supposed to remove more than one consecutive space - but also deletes my returns ...
$string = preg_replace('/\n\n\n+/', '\n\n', $string); // using this one by itself does not do as expected and removes all returns ...
It seems first line already gets rid of more than one spaces AND all returns ... Which is strange. Not sure than I am doing it right ...
Because \s will also match newline characters. So i suggest you to use \h for matching any kind of horizontal spaces.
$string = preg_replace('/\h\h+/', ' ', $string);
\s match any white space character [\r\n\t\f ]
See the deifinition of \s.It includes \n.Use
\h matches any horizontal whitespace character (equal to [[:blank:]])
Use \h for horizontal whitespaces.
For those of you who will need it, that's how you remove two carriage returns from a textarea.
preg_replace('/\n\r(\n\r)+/', "\n\r", $str);
For the space issue, as it has been posted above, replace \s by \h

Regex to add spacing between sentences in a string in php

I use a spanish dictionary api that returns definitions with small issues. This specific problem happens when the definition has more than 1 sentence. Sometimes the sentences are not properly separated by a space character, so I receive something like this:
This is a sentence.Some other sentence.Sometimes there are no spaces between dots. See?
Im looking for a regex that would replace "." for ". " when the dot is immediately followed by a char different than the space character. The preg_replace() should return:
This is a sentence. Some other sentence. Sometimes there are no spaces between dots. See?
So far I have this:
echo preg_replace('/(?<=[a-zA-Z])[.]/','. ',$string);
The problem is that it also adds a space when there is already a space after the dot. Any ideas? Thanks!
Try this regular expression:
echo preg_replace('/(?<!\.)\.(?!(\s|$|\,|\w\.))/', '. ', $string);
echo preg_replace( '/\.([^, ])/', '. $1', $string);
It works!
You just need to apply a look-ahead to so adds a space if the next character is something other than a space or is not the end of the string:
$string = preg_replace('/(?<=[a-zA-Z])[.](?![\s$])/','. ',$string);

Remove whitespace around certain character with preg_replace

I have a string where I want to remove all the whitespace around a certain character using preg_replace. In my case this character is /.
For example:
first part / second part would become first part/second part
Or let's say that character is : now:
first part : second part would become first part:second part
I couldn't find an example on how to do this... Thanks!
$string = preg_replace("/\s*([\/:])\s*/", "$1", $string);
Explanation:
\s* means any amount (*) of whitespace (\s)
[\/:] is either a / or a :. If you want another character, just add it here.
the brackets are a capture group which you reference with the $1 meaning that if it matches a : then the $1 will mean :.
Replace : with your character.
$string = preg_replace("/\s*:\s*/", ":", $string);
In english:
Replace any amount of whitespace (including 0), then a : and then any amount of whitespace again, by just a :.
match optional space followed by your character (captured in brackets) followed by another optional space and then replace by your captured character
preg_replace('/\s*(:)\s*/',"$1",$str);

How to replace one or more consecutive spaces with one single character?

I want to generate the string like SEO friendly URL. I want that multiple blank space to be eliminated, the single space to be replaced by a hyphen (-), then strtolower and no special chars should be allowed.
For that I am currently the code like this:
$string = htmlspecialchars("This Is The String");
$string = strtolower(str_replace(htmlspecialchars((' ', '-', $string)));
The above code will generate multiple hyphens. I want to eliminate that multiple space and replace it with only one space. In short, I am trying to achieve the SEO friendly URL like string. How do I do it?
You can use preg_replace to replace any sequence of whitespace chars with a dash...
$string = preg_replace('/\s+/', '-', $string);
The outer slashes are delimiters for the pattern - they just mark where the pattern starts and ends
\s matches any whitespace character
+ causes the previous element to match 1 or more times. By default, this is 'greedy' so it will eat up as many consecutive matches as it can.
See the manual page on PCRE syntax for more details
echo preg_replace('~(\s+)~', '-', $yourString);
What you want is "slugify" a string. Try a search on SO or google on "php slugify" or "php slug".

Categories