Jump to content

Letters and Spaces Only


crackpanda

Recommended Posts

Hey, could someone help me put together a statement to check a string for letters and spaces and return true or false (i want see if the string has letters and spaces, which would be normal, or if it also contains numbers and these guys !@#$^& e.t.c, which would be unwanted)

 

- Thank you.  ;D

Link to comment
https://forums.phpfreaks.com/topic/147463-letters-and-spaces-only/
Share on other sites

What you might want to use is a preg_match_all  (detailed info here http://us3.php.net/preg_match_all)

 

$html = "<b>bold text</b><a href=howdy.html>click me</a>";

 

preg_match_all("/(<([\w]+)[^>]*>)(.*)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER);

 

You could then replace offending characters with

preg_replace

 

<?php

$string = 'The quick brown fox jumped over the lazy dog.';

$patterns[0] = '/quick/';

$patterns[1] = '/brown/';

$patterns[2] = '/fox/';

$replacements[2] = 'bear';

$replacements[1] = 'black';

$replacements[0] = 'slow';

echo preg_replace($patterns, $replacements, $string);

?>

 

 

Hope that helps.

What you might want to use is a preg_match_all  (detailed info here http://us3.php.net/preg_match_all)

 

$html = "<b>bold text</b><a href=howdy.html>click me</a>";

 

preg_match_all("/(<([\w]+)[^>]*>)(.*)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER);

 

You could then replace offending characters with

preg_replace

 

<?php

$string = 'The quick brown fox jumped over the lazy dog.';

$patterns[0] = '/quick/';

$patterns[1] = '/brown/';

$patterns[2] = '/fox/';

$replacements[2] = 'bear';

$replacements[1] = 'black';

$replacements[0] = 'slow';

echo preg_replace($patterns, $replacements, $string);

?>

 

 

Hope that helps.

 

I was looking for something more simple such as an ereg statement, i just can't figure out how to set it up myself. I dont want to replace anything, i just want a true or false on a string.

 

For example:

 

im expecting: hello hello

 

or: Hello Hello

 

but i want to give an error if something such as:

 

Hello2 Hello

 

or

 

Hello!

 

is given.

 

The code you gave me over-complicates the result, but thank you for helping. :)

A simple

 

<?php
if (preg_match('~^[a-z ]+$~iD', $str)) {
//do something
}
?>

 

will do :)^ and $ makes it check the whole string, and the pattern modifiers i and D makes the search case insensitive and makes sure $ truly is the end, respectively.

 

That is godly, thank you very much, that was exactly the puzzle piece i needed.  ;D

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.