如何在PHP中获取特定的字符串?

时间:2015-04-07 02:34:27

标签: javascript php jquery string algorithm

假设我有以下用户DN 我需要从下面的字符串中获取唯一的DC字符串和值。

示例1:

CN=xxx,OU=xxx xxx,OU=aaa bbb,DC=ABC,DC=com

结果1:

DC=ABC,DC=com

示例2:由 Sam J Levy

创建
OU=Departments,DC=college,DC=school,DC=edu

结果2:

DC=college,DC=school,DC=edu

有没有办法让整个DC字符串如上面的结果Sample Demo

1 个答案:

答案 0 :(得分:2)

<强> PHP

您可以将substrstrpos合并为:

<?php

$string = 'CN=xxx,OU=xxx xxx,OU=aaa bbb,DC=ABC,DC=com';

echo substr($string, strpos($string, 'DC='));
?>

输出:

  

DC = ABC,DC = COM

示例2:

<?php

$string = 'OU=Departments,DC=college,DC=school,DC=edu';

echo substr($string, strpos($string, 'DC='));
?>

输出:

  

DC =学院,DC =学校,DC = EDU

<强> JAVASCRIPT

您可以将此strpos功能与substringlength

一起使用
<script>

function strpos(haystack, needle, offset) {
  var i = (haystack + '')
    .indexOf(needle, (offset || 0));
  return i === -1 ? false : i;
}

var string = 'CN=xxx,OU=xxx xxx,OU=aaa bbb,DC=ABC,DC=com';
var pos = strpos(string, 'DC=');
var info = string.substring(pos, string.length);
alert(info);

</script>

示例2:

<script>

function strpos(haystack, needle, offset) {
  var i = (haystack + '')
    .indexOf(needle, (offset || 0));
  return i === -1 ? false : i;
}

var string = 'OU=Departments,DC=college,DC=school,DC=edu';
var pos = strpos(string, 'DC=');
var info = string.substring(pos, string.length);
alert(info);

</script>

阅读更多内容:

  

http://php.net/manual/en/function.substr.php

     

http://php.net/manual/en/function.strpos.php

     

http://phpjs.org/functions/strpos/