使用PHP在字符串中查找字符串并从中获取一些值

时间:2013-03-21 13:58:58

标签: php regex string strpos

我有一个这样的字符串:

$string = 'this is some random text 
  <div class="myClass" title="myTitle">this is some random text
  again</div> and some more randome text';

现在我想从中删除此内容:

<div class="myClass" title="myTitle">this is some random text again</div>

但同时我想存储class的值和title

的值

关于如何解决这个问题的任何想法?

1 个答案:

答案 0 :(得分:1)

以下是您的示例具体显示的示例脚本:

<?php
  $string = 'this is some random text <div class="myClass" title="myTitle">
             this is some random text again</div> and some more randome text';
  preg_match('/class=\"(\w{1,})\"\stitle=\"(\w{1,})\"/i', $string, $matches);
  echo "Class: {$matches[1]}\n";
  echo "Title: {$matches[2]}\n";
?>

输出:

marks-mac-pro:~ mstanislav$ php regex.php 
Class: myClass
Title: myTitle

您可能需要针对其他用途进行调整和/或确保与HTML属性的命名约定兼容。