FEATURE Add Convert::raw2htmlid()

This commit is contained in:
Will Rossiter 2013-05-26 11:01:46 +12:00
parent 5d76048275
commit 736bde8fe5
2 changed files with 49 additions and 9 deletions

View File

@ -43,22 +43,49 @@ class Convert {
}
/**
* Convert a value to be suitable for an HTML attribute.
*
* This is useful for converting human readable values into
* a value suitable for an ID or NAME attribute.
* Convert a value to be suitable for an HTML ID attribute. Replaces non
* supported characters with a space.
*
* @see http://www.w3.org/TR/REC-html40/types.html#type-cdata
* @uses Convert::raw2att()
*
* @param array|string $val String to escape, or array of strings
*
* @return array|string
*/
public static function raw2htmlname($val) {
if(is_array($val)) {
foreach($val as $k => $v) $val[$k] = self::raw2htmlname($v);
foreach($val as $k => $v) {
$val[$k] = self::raw2htmlname($v);
}
return $val;
} else {
return preg_replace('/[^a-zA-Z0-9\-_:.]+/','', $val);
return self::raw2att($val);
}
}
/**
* Convert a value to be suitable for an HTML ID attribute. Replaces non
* supported characters with an underscore.
*
* @see http://www.w3.org/TR/REC-html40/types.html#type-cdata
*
* @param array|string $val String to escape, or array of strings
*
* @return array|string
*/
public static function raw2htmlid($val) {
if(is_array($val)) {
foreach($val as $k => $v) {
$val[$k] = self::raw2htmlid($v);
}
return $val;
} else {
return trim(preg_replace(
'/_+/', '_', preg_replace('/[^a-zA-Z0-9\-_:.]+/','_', $val)),
'_'
);
}
}

View File

@ -1,11 +1,15 @@
<?php
/**
* Test various functions on the {@link Convert} class.
*
* @package framework
* @subpackage tests
*/
class ConvertTest extends SapphireTest {
protected $usesDatabase = false;
/**
* Tests {@link Convert::raw2att()}
*/
@ -81,9 +85,18 @@ class ConvertTest extends SapphireTest {
'Newlines are retained. They should not be replaced with <br /> as it is not XML valid');
}
public function testRaw2HtmlName() {
/**
* Tests {@link Convert::raw2htmlid()}
*/
public function testRaw2HtmlID() {
$val1 = 'test test 123';
$this->assertEquals('testtest123', Convert::raw2htmlname($val1));
$this->assertEquals('test_test_123', Convert::raw2htmlid($val1));
$val1 = 'test[test][123]';
$this->assertEquals('test_test_123', Convert::raw2htmlid($val1));
$val1 = '[test[[test]][123]]';
$this->assertEquals('test_test_123', Convert::raw2htmlid($val1));
}
/**