User login

Drupal function for stripping spaces and unsafe things to make the system machine name

bangpound:
what's a function that does the job of replacing spaces with underscores, lowering case of letters, stripping out non-alphanumerics?
less complex than pathauto. i need to do what the content_type.js file does, but in php

Not what we're looking for (from form.inc):

<?php
  $id
= str_replace(array('][', '_', ' '), '-', $id);
?>

A possibility:

<?php
function zen_id_safe($string) {
  if (
is_numeric($string{0})) {
   
// If the first character is numeric, add 'n' in front
   
$string = 'n'. $string;
  }
  return
strtolower(preg_replace('/[^a-zA-Z0-9-]+/', '-', $string));
}
?>

What bangpound is using in the fielderized taxonomy module:

<?php
   
'field_name' => 'term_'. preg_replace('/[^a-z0-9]+/', '_', strtolower($edit['name'])),
?>

Crell: Have a toggle for underscore or hyphen, and option to check for unique.

/**
* Take a user-entered name and make it machine-safe.
*
* Replace spaces and all unknown characters with underscores and lowercase.
*
* @TODO get this into common.inc
*/
function drupal_system_name($string) {
return preg_replace('/[^a-z0-9]+/', '_', strtolower($string));
}

But we need more.

Crell also suggested I use a flag if the string should be unique, but there's no clean way I see for this function to know where its string is going (and so know what is there already). No $unique = FALSE flag.

function drupal_system_string($string, $replacement = '_') {
return preg_replace('/[^a-z0-9]+/', $replacement, strtolower($string));
}

Resolution

Searched words: 
change spaces to dash drupal function underscore dashes spaces drupal function replace spaces test if first character alpha php php first character alpha preg replace make sure first character alpha

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <blockquote> <small> <h2> <h3> <h4> <h5> <h6> <sub> <sup> <p> <br> <strike> <table> <tr> <td> <thead> <th> <tbody> <tt> <output>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.