regex - PHP Remove all non letters

675

I have several strings that look like this:

Lasklé
Jones & Jon

I am trying to send them via the foursquare API to be matched, however it is failing with these characters. Is there a way to sanitise these so they only include English letters i.e. the results would be:

Lasklé
Jones Jon

As it appears usingfile_get_contents requests both with the 'é' and the '&' in the URL is causing issues.

I checked how the request was sent and realised that the '&' is uneeded and is causing the issues, is it possible to remove all non Letters/Numbers from the name?

22

Answer

Solution:

What do the strings look like before you pass them? If your string looks like 'Lasklé' then I think you are using the wrong character set when reading the string, try using UTF-8.

If the string looks correct before you pass it on you should try urlencode the string first.

934

Answer

Solution:

you can use preg_replace() function to replace the part of string using regex

to keep only letters you can use as follow it will also remove space( add \s from expression to keep space)

preg_replace('/[^a-zA-Z]/','',$string);

to keep space in the string or any character to keep you can add it in []

 preg_replace('/[^a-zA-Z\s]/','',$string);
611

Answer

Solution:

Use this to escape (space and '-'). Good for making a custom URL

$string=preg_replace("/[^A-Za-z0-9\s\/\-]/", '', $string);

People are also looking for solutions to the problem: javascript - How to use Babel or webpack in a old php site with separate modules

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.