Magento 2 Remove Special Characters from String: Best Solution

0
439
Magento 2 Remove Special Characters from String

In this article, you going to see solution for Magento 2 remove special characters from string in depth and step by step.

If you are looking for this topic then you are at right place.

Let’s start with topic of Magento 2 Remove Special Characters from String

In Magento 2, there is file called Match.php file which contain CONSTANT like SPECIAL_CHARACTERS.

Along with this constant all special character are also present.

With help of this it become very easy to remove special characters.

The path of this file is given below.

Magento\Framework\Search\Adapter\Mysql\Query\Builder\Match.php

With help of the default Magento constant you can remove or replace special character with some other character.

In the file called Match.php consist a constant declaration given below.

Below is constant code snippet.

const SPECIAL_CHARACTERS = ‘-+~/\\<>\'”:*$#@()!,.?`=%&^’;

With the help of below code snippet you come to know that if you want to modify a string with special character to some custom value or blank.

<?php
 $originalString = "SampleString1$23?45&789^1";

 $replaceSymbols =  str_split( \Magento\Framework\Search\Adapter\Mysql\Query\Builder\Match::SPECIAL_CHARACTERS, 1);
 $string = str_replace($replaceSymbols, ' ', $originalString));
 echo $string; 

Below is the out put in which remove all special character with space.

OUTPUT : “SampleString1 23 45 789 1”.

Magento 2 Create CSV file and Download Programmatically

Conclusion :

Using the above file Remove Special Characters from String.

I hope you like this article and if you think that i have missing something, please comment below.