PageRenderTime 47ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/en/core-utility-libraries/string.rst

https://gitlab.com/albertkeba/docs
ReStructuredText | 300 lines | 217 code | 83 blank | 0 comment | 0 complexity | 126ba86ad545838bc909084d0665c66d MD5 | raw file
  1. String
  2. ######
  3. .. php:class:: String
  4. The String class includes convenience methods for creating and
  5. manipulating strings and is normally accessed statically. Example:
  6. ``String::uuid()``.
  7. If you need :php:class:`TextHelper` functionalities outside of a ``View``,
  8. use the ``String`` class::
  9. class UsersController extends AppController {
  10. public $components = array('Auth');
  11. public function afterLogin() {
  12. App::uses('String', 'Utility');
  13. $message = $this->User->find('new_message');
  14. if (!empty($message)) {
  15. // notify user of new message
  16. $this->Session->setFlash(__('You have a new message: %s', String::truncate($message['Message']['body'], 255, array('html' => true))));
  17. }
  18. }
  19. }
  20. .. versionchanged:: 2.1
  21. Several methods from :php:class:`TextHelper` have been moved to
  22. ``String`` class.
  23. .. php:staticmethod:: uuid()
  24. The UUID method is used to generate unique identifiers as per
  25. :rfc:`4122`. The UUID is a
  26. 128bit string in the format of
  27. 485fc381-e790-47a3-9794-1337c0a8fe68.
  28. ::
  29. String::uuid(); // 485fc381-e790-47a3-9794-1337c0a8fe68
  30. .. php:staticmethod:: tokenize($data, $separator = ',', $leftBound = '(', $rightBound = ')')
  31. Tokenizes a string using ``$separator``, ignoring any instance of
  32. ``$separator`` that appears between ``$leftBound`` and ``$rightBound``.
  33. This method can be useful when splitting up data in that has regular
  34. formatting such as tag lists::
  35. $data = "cakephp 'great framework' php";
  36. $result = String::tokenize($data, ' ', "'", "'");
  37. // result contains
  38. array('cakephp', "'great framework'", 'php');
  39. .. php:staticmethod:: insert($string, $data, $options = array())
  40. The insert method is used to create string templates and to allow
  41. for key/value replacements::
  42. String::insert('My name is :name and I am :age years old.', array('name' => 'Bob', 'age' => '65'));
  43. // generates: "My name is Bob and I am 65 years old."
  44. .. php:staticmethod:: cleanInsert($string, $options = array())
  45. Cleans up a ``String::insert`` formatted string with given $options
  46. depending on the 'clean' key in $options. The default method used
  47. is text but html is also available. The goal of this function is to
  48. replace all whitespace and unneeded markup around placeholders that
  49. did not get replaced by Set::insert.
  50. You can use the following options in the options array::
  51. $options = array(
  52. 'clean' => array(
  53. 'method' => 'text', // or html
  54. ),
  55. 'before' => '',
  56. 'after' => ''
  57. );
  58. .. php:staticmethod:: wrap($text, $options = array())
  59. Wraps a block of text to a set width, and indent blocks as well.
  60. Can intelligently wrap text so words are not sliced across lines::
  61. $text = 'This is the song that never ends.';
  62. $result = String::wrap($text, 22);
  63. // returns
  64. This is the song
  65. that never ends.
  66. You can provide an array of options that control how wrapping is done. The
  67. supported options are:
  68. * ``width`` The width to wrap to. Defaults to 72.
  69. * ``wordWrap`` Whether or not to wrap whole words. Defaults to true.
  70. * ``indent`` The character to indent lines with. Defaults to ''.
  71. * ``indentAt`` The line number to start indenting text. Defaults to 0.
  72. .. start-string
  73. .. php:method:: highlight(string $haystack, string $needle, array $options = array() )
  74. :param string $haystack: The string to search.
  75. :param string $needle: The string to find.
  76. :param array $options: An array of options, see below.
  77. Highlights ``$needle`` in ``$haystack`` using the
  78. ``$options['format']`` string specified or a default string.
  79. Options:
  80. - 'format' - string The piece of HTML with that the phrase will be
  81. highlighted
  82. - 'html' - bool If true, will ignore any HTML tags, ensuring that
  83. only the correct text is highlighted
  84. Example::
  85. // called as TextHelper
  86. echo $this->Text->highlight(
  87. $lastSentence,
  88. 'using',
  89. array('format' => '<span class="highlight">\1</span>')
  90. );
  91. // called as String
  92. App::uses('String', 'Utility');
  93. echo String::highlight(
  94. $lastSentence,
  95. 'using',
  96. array('format' => '<span class="highlight">\1</span>')
  97. );
  98. Output::
  99. Highlights $needle in $haystack <span class="highlight">using</span>
  100. the $options['format'] string specified or a default string.
  101. .. php:method:: stripLinks($text)
  102. Strips the supplied ``$text`` of any HTML links.
  103. .. php:method:: truncate(string $text, int $length=100, array $options)
  104. :param string $text: The text to truncate.
  105. :param int $length: The length, in characters, beyond which the text should be truncated.
  106. :param array $options: An array of options to use.
  107. If ``$text`` is longer than ``$length`` characters, this method truncates it
  108. at ``$length`` and adds a prefix consisting of ``'ellipsis'``, if defined.
  109. If ``'exact'`` is passed as ``false``, the truncation will occur at the
  110. first whitespace after the point at which ``$length`` is exceeded. If
  111. ``'html'`` is passed as ``true``, HTML tags will be respected and will not
  112. be cut off.
  113. ``$options`` is used to pass all extra parameters, and has the
  114. following possible keys by default, all of which are optional::
  115. array(
  116. 'ellipsis' => '...',
  117. 'exact' => true,
  118. 'html' => false
  119. )
  120. Example::
  121. // called as TextHelper
  122. echo $this->Text->truncate(
  123. 'The killer crept forward and tripped on the rug.',
  124. 22,
  125. array(
  126. 'ellipsis' => '...',
  127. 'exact' => false
  128. )
  129. );
  130. // called as String
  131. App::uses('String', 'Utility');
  132. echo String::truncate(
  133. 'The killer crept forward and tripped on the rug.',
  134. 22,
  135. array(
  136. 'ellipsis' => '...',
  137. 'exact' => false
  138. )
  139. );
  140. Output::
  141. The killer crept...
  142. .. versionchanged:: 2.3
  143. ``ending`` has been replaced by ``ellipsis``. ``ending`` is still used in 2.2.1
  144. .. php:method:: tail(string $text, int $length=100, array $options)
  145. :param string $text: The text to truncate.
  146. :param int $length: The length, in characters, beyond which the text should be truncated.
  147. :param array $options: An array of options to use.
  148. If ``$text`` is longer than ``$length`` characters, this method removes an initial
  149. substring with length consisting of the difference and prepends a suffix
  150. consisting of ``'ellipsis'``, if defined. If ``'exact'`` is passed as
  151. ``false``, the truncation will occur at the first whitespace prior to the
  152. point at which truncation would otherwise take place.
  153. ``$options`` is used to pass all extra parameters, and has the
  154. following possible keys by default, all of which are optional::
  155. array(
  156. 'ellipsis' => '...',
  157. 'exact' => true
  158. )
  159. .. versionadded:: 2.3
  160. Example::
  161. $sampleText = 'I packed my bag and in it I put a PSP, a PS3, a TV, ' .
  162. 'a C# program that can divide by zero, death metal t-shirts'
  163. // called as TextHelper
  164. echo $this->Text->tail(
  165. $sampleText,
  166. 70,
  167. array(
  168. 'ellipsis' => '...',
  169. 'exact' => false
  170. )
  171. );
  172. // called as String
  173. App::uses('String', 'Utility');
  174. echo String::tail(
  175. $sampleText,
  176. 70,
  177. array(
  178. 'ellipsis' => '...',
  179. 'exact' => false
  180. )
  181. );
  182. Output::
  183. ...a TV, a C# program that can divide by zero, death metal t-shirts
  184. .. php:method:: excerpt(string $haystack, string $needle, integer $radius=100, string $ellipsis="...")
  185. :param string $haystack: The string to search.
  186. :param string $needle: The string to excerpt around.
  187. :param int $radius: The number of characters on either side of $needle you want to include.
  188. :param string $ellipsis: Text to append/prepend to the beginning or end of the result.
  189. Extracts an excerpt from ``$haystack`` surrounding the ``$needle``
  190. with a number of characters on each side determined by ``$radius``,
  191. and prefix/suffix with ``$ellipsis``. This method is especially handy for
  192. search results. The query string or keywords can be shown within
  193. the resulting document. ::
  194. // called as TextHelper
  195. echo $this->Text->excerpt($lastParagraph, 'method', 50, '...');
  196. // called as String
  197. App::uses('String', 'Utility');
  198. echo String::excerpt($lastParagraph, 'method', 50, '...');
  199. Output::
  200. ... by $radius, and prefix/suffix with $ellipsis. This method is
  201. especially handy for search results. The query...
  202. .. php:method:: toList(array $list, $and='and')
  203. :param array $list: Array of elements to combine into a list sentence.
  204. :param string $and: The word used for the last join.
  205. Creates a comma-separated list where the last two items are joined
  206. with 'and'. ::
  207. // called as TextHelper
  208. echo $this->Text->toList($colors);
  209. // called as String
  210. App::uses('String', 'Utility');
  211. echo String::toList($colors);
  212. Output::
  213. red, orange, yellow, green, blue, indigo and violet
  214. .. end-string
  215. .. meta::
  216. :title lang=en: String
  217. :keywords lang=en: array php,array name,string options,data options,result string,class string,string data,string class,placeholders,default method,key value,markup,rfc,replacements,convenience,templates