Christian Beltran
Christian Beltran

Reputation: 87

How to replace the first three character on a string

How to replace the first three special character in my string.? This is the sample.

$string = "~~MASTER FOR OILCHEM; ETD - MID OF JUNE~~";
 echo preg_replace("/[^a-zA-Z0-9]/", "", $string);

The outout will be :

MASTERFOROILCHEMETDMIDOFJUNE

But I want the fist three special character to be replace. So the output will be :

MASTER FOR OILCHEM; ETD - MID OF JUNE~~

Upvotes: 0

Views: 93

Answers (2)

MaGlNet
MaGlNet

Reputation: 13

The following code searches for 0 up to 3 non word characters and replaces them with an empty string:

$string = "~~MASTER FOR OILCHEM; ETD - MID OF JUNE~~";
echo preg_replace("/^\W{0,3}/", "", $string);

The above PHP outputs the following:

MASTER FOR OILCHEM; ETD - MID OF JUNE~~

See https://3v4l.org/lFKXV for a live example.

And regarding Regular Expressions, you should try this great tool.
https://regex101.com/r/pD7vR7/1

Upvotes: 1

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21422

Instead of regex you can simply use substr like as

$string = "~~MASTER FOR OILCHEM; ETD - MID OF JUNE~~";
echo substr($string,2);

Upvotes: 1

Related Questions