Location: PHPKode > scripts > PHPBiDi > phpbidi/example.php
<html>
  <head>
    <title>Examples for PHPBiDi</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  </head>
  <body>
    <?php

// We need to include phpbidi.php
require_once (realpath(dirname(__FILE__)) . '/phpbidi.php');

    // Get the text you want to process first.
    // Let's say it's already in variable $txt and it's left-to-right text.
    $txt = 'I love you. Mi amas vin. Σε αγαπώ. Обичам те.
Ég elska þig. Я тебя люблю. Anh yêu em. Seni seviyorum. Ich liebe Dich.';
    echo $txt;
    echo "<br /><br />\n\n\n";

    // First create the object that will handle the text.
    // Use 'true' if it's HTML.
    $handle = new PHPBiDi($txt, false);

    // The main processing has already taken place. Now, we need to decide
    // where to break the lines and instruct PHPBiDi to return each line
    // in right-to-left order, where appropriate. Of course, in this case
    // the lines returned are identical to the original as our text does
    // not contain any right-to-left characters.
    // Let's say that we decide to break the lines at \n.
    // Function getResultText() returns the original input.
    $lines = preg_split('/\r\n/', $handle->getResultNewText());
    $start = 0;
    $new_text = '';
    foreach($lines as $line) {

        // To get the line propersly reversed where appropriate we need
        // to use function getLine() which we feed with
        // $start: the offset where the line starts in the original
        // paragraph (if the text contains RTL characters and more than
        // one paragraph) or text.
        // $length: how many characters the line contains
        $length = strlen($line);
        $new_text.= $handle->getLine($start, $length) . "\r\n";
        $start+= $length;
    }
    echo $new_text;
    echo "<br /><br /><hr />\n\n\n";

    // Now, let's say that we've got multiple paragraphs.
    $txt = 'I love you. Mi amas vin. Σε αγαπώ. Обичам те.
Ég elska þig. Я тебя люблю. Anh yêu em. Seni seviyorum. Ich liebe Dich.

The 2007 UEFA Champions League Final was a football match played at the
Olympic Stadium in Athens, Greece, on 23 May 2007, to decide the winner
of the 2006–07 UEFA Champions League. English club Liverpool faced Italy\'s
A.C. Milan in a repeat match-up of the 2005 final. A.C. Milan won the match
2–1, after two goals from man of the match Filippo Inzaghi.

Η Ανδρομάχη ήταν κόρη του Ηετίωνα, βασιλιά της «Υποπλακίης Θήβης», όπως την
ονομάζει ο Όμηρος στην Ιλιάδα, επειδή ήταν μια πόλη στους πρόποδες του όρους
Πλάκος, στον κάμπο του Αδραμυττίου. Αδελφός της Ανδρομάχης ήταν ο Πόδης, που
σκοτώθηκε από τον Μενέλαο. Ωστόσο, στην Ιλιάδα (ραψωδία Ζ) η Ανδρομάχη
παρουσιάζεται να λέει πως και οι επτά αδελφοί της σκοτώθηκαν από τον Αχιλλέα.

Birdumo au birdorigardado estas observado kaj studo de birdoj per simple okula
rigardo au per vida plibonigo danke al uzado de binokloj. Plej granda parto de
birdumantoj au birdorigardantoj plenumas tiun agadon pro distraj au sociaj
kialoj malkiel ornitologoj kiuj estas enmetitaj en pli formala scienca studo
de birdoj.';
    echo $txt;
    echo "<br /><br />\n\n\n";
    $handle = new PHPBiDi($txt, false);
    echo myLines($handle);
    echo "<br /><br /><hr />\n\n\n";

    // So far nothing special has happened.
    // Let's make things a bit more interesting...
    $txt = 'אחרי ההפסד 0-1 לסכנין, משער של מאור בוזגלו בדקה ה-90, הגיע ארקדי גיידמק לאזור חדר ההלבשה של בית"ר. הוא היה צרוד, לאחר שלאורך כל 90 הדקות עודד את שחקניו ושר בגנות ההתאחדות ממקום מושבו ביציע המזרחי הריק. כשעמד מול העיתונאים, הוא חשב פעמיים על כל תשובה לפני שענה. כשנשאל על מאמן הקבוצה, הציץ לעבר יועצו ולבסוף ענה בהחלטיות: "יצחק שום יאמן את בית"ר גם בעונה הבאה. הוא אדם טוב והבעיה איננה בו".

أبو ظبي-العرب اونلاين- وكالات: حقق المنتخب المصرى لكرة القدم فوزا معنويا على نظيره مالى بتغلبه عليه 1-0 فى المباراة الودية الدولية التى جمعت بينهما الخميس على ملعب "أل نهيان" بنادى الوحدة بالعاصمة الإماراتية أبو ظبي.';

    // Most browsers automatically render RTL text appropriately.
    // So, the following text will read fine in your browser. However,
    // the order of characters is LTR.
    echo $txt;
    echo "<br /><br />\n\n\n";
    $handle = new PHPBiDi($txt, false);
    echo myLines($handle);
    echo "<br /><br /><hr />\n\n\n";


  // Now, let's have a look at some HTML text.
  $txt = '<p>The <b>2007 UEFA Champions League Final</b> was a <a href="/wiki/Association_football" title="Association football">football</a> match played at the <a href="/wiki/Olympic_Stadium_%28Athens%29" title="Olympic Stadium (Athens)">Olympic Stadium</a> in <a href="/wiki/Athens" title="Athens">Athens</a>, <a href="/wiki/Greece" title="Greece">Greece</a> on <a href="/wiki/May_23" title="May 23">23 May</a> <a href="/wiki/2007" title="2007">2007</a>, to decide the winner of the <a href="/wiki/UEFA_Champions_League_2006-07" title="UEFA Champions League 2006-07">2006–07</a> <a href="/wiki/UEFA_Champions_League" title="UEFA Champions League">UEFA Champions League</a>. <a href="/wiki/Football_in_England" title="Football in England">English</a> club <a href="/wiki/Liverpool_F.C." title="Liverpool F.C.">Liverpool</a> faced <a href="/wiki/Football_in_Italy" title="Football in Italy">Italy</a>\'s <a href="/wiki/A.C._Milan" title="A.C. Milan">A.C. Milan</a> in a repeat match-up of the <a href="/wiki/2005_UEFA_Champions_League_Final" title="2005 UEFA Champions League Final">2005 final</a>. A.C. Milan won the match 2–1, after two goals from man of the match <a href="/wiki/Filippo_Inzaghi" title="Filippo Inzaghi">Filippo Inzaghi</a>.</p>

<p>Before 2007, A.C. Milan\'s last triumph had been in the <a href="/wiki/2003_UEFA_Champions_League_Final" title="2003 UEFA Champions League Final">2003 final</a>, while Liverpool\'s was against Milan in the <a href="/wiki/2005_UEFA_Champions_League_Final" title="2005 UEFA Champions League Final">2005 final</a>. Liverpool and A.C. Milan started their UEFA Champions League campaigns in the Third Qualifying round; both sides progressed to the group stages and won their respective groups. Liverpool and A.C. Milan beat former champions on their way to the final. A.C. Milan beat <a href="/wiki/1967_European_Cup_Final" title="1967 European Cup Final">1967</a> champions <a href="/wiki/Celtic_F.C." title="Celtic F.C.">Celtic</a>, four-time champions <a href="/wiki/FC_Bayern_Munich" title="FC Bayern Munich">FC Bayern Munich</a>, and <a href="/wiki/1999_UEFA_Champions_League_Final" title="1999 UEFA Champions League Final">1999</a> winners <a href="/wiki/Manchester_United_F.C." title="Manchester United F.C.">Manchester United</a>. Liverpool beat defending champions <a href="/wiki/FC_Barcelona" title="FC Barcelona">FC Barcelona</a> and <a href="/wiki/1988_European_Cup_Final" title="1988 European Cup Final">1988</a> winners <a href="/wiki/PSV_Eindhoven" title="PSV Eindhoven">PSV Eindhoven</a>. Liverpool also beat <a href="/wiki/Chelsea_F.C." title="Chelsea F.C.">Chelsea F.C.</a> in the semi-final stage for the second time in three years.</p>

<p>Before the match there were ticketing problems due to a large number of fans gaining entry to the stadium without tickets. After the match, a UEFA spokesman accused Liverpool of having the worst <a href="/wiki/Association_football_culture#Fans" title="Association football culture">fans</a> in Europe, a claim later denied by UEFA president <a href="/wiki/Michel_Platini" title="Michel Platini">Michel Platini</a>.</p>';

  echo $txt;
  echo "<br /><br />\n\n\n";
  $handle = new PHPBiDi($txt, true);

  // You can get two versions of HTML text: with or without markup tags.
  echo myLines($handle, true, false);
  echo "<br /><br /><hr />\n\n\n";
  $handle->resetParagraph();
  echo myLines($handle, false, false);
  echo "<br /><br /><hr />\n\n\n";
  $handle->resetParagraph();
  echo myLinesOrig($handle, true, true);
  echo "<br /><br /><hr />\n\n\n";
  $handle->resetParagraph();
  echo myLinesOrig($handle, false, true);
  echo "<br /><br /><hr />\n\n\n";


    $txt = 'אחרי ההפסד 0-1 לסכנין, <a href="http://www.test.com/"><b>משער של מאור בוזגלו בדקה ה-90 abcd ab</b></a> ffl, הגיע ארקדי גיידמק לאזור חדר (ההלבשה של בית"ר). <a href="http://www.test.com/">הוא היה צרוד</a>, לאחר שלאורך כל 90 הדקות עודד את שחקניו ושר <a href="http://www.test.com/">בגנות ההתאחדות</a> ממקום מושבו ביציע המזרחי הריק. <a href="http://www.test.com/">כשעמד מול העיתונאים, הוא חשב פעמיים על כל תשובה לפני שענה.</a> כשנשאל על מאמן הקבוצה, הציץ לעבר יועצו ולבסוף ענה בהחלטיות: "יצחק שום יאמן את בית"ר גם בעונה הבאה. הוא אדם טוב והבעיה איננה בו".

<a href="http://www.test.com/">أبو ظبي-العرب اونلاين- وكالات</a>: حقق المنتخب المصرى لكرة القدم فوزا (معنويا على نظيره مالى بتغلبه عليه) <a href="http://www.test.com/">1-0</a> فى المباراة الودية الدولية التى جمعت بينهما الخميس على ملعب "أل نهيان" بنادى الوحدة <a href="http://www.test.com/">بالعاصمة الإماراتية أبو</a> ظبي.';
  echo $txt;
  echo "<br /><br />\n\n\n";
  $handle = new PHPBiDi($txt, true);

  // You can get two versions of HTML text: with or without markup tags.
  echo myLines($handle, true, false);
  echo "<br /><br /><hr />\n\n\n";
  $handle->resetParagraph();
  echo myLines($handle, false, false);
  echo "<br /><br /><hr />\n\n\n";
  $handle->resetParagraph();
  echo myLinesOrig($handle, true, true);
  echo "<br /><br /><hr />\n\n\n";
  $handle->resetParagraph();
  echo myLinesOrig($handle, false, true);
  echo "<br /><br /><hr />\n\n\n";

function myLines(&$handle, $tags = false, $input = false) {

  // constant('UTF8PATTERN') helps count utf-8 encoded characters
  $pattern = constant('UTF8PATTERN');

  // You can get the number of paragraphs through getResultNum().
  for ($i = 0;$i < $handle->getResultNum();$i++) {

    // Let's say that this time we decide to break lines at 80
    // characters per line or less.
    // Function getResultNewText() returns the text as it has been
    // changed at the end of the first stage of processing, i.e.
    // in this case, without any \r\n.
    preg_match_all($pattern, $handle->getResultNewText(), $matches);
    $lines = array();
    $space = 0;
    $start = 0;
    $counter = 0;
    $line = '';
    $word = '';
    for ($j = 0;$j < count($matches[0]);$j++) {
      if ($matches[0][$j] == ' ') {
        $line.= $word;
        $word = '';
        $start = $j;
      }
      if ($counter > 79) {
        $lines[] = $line . ' ';
        $j = $start;
        $counter = 0;
        $line = '';
        $word = '';
      } else {
        $word.= $matches[0][$j];
      }
      $counter++;
    }

    // We shouldn't forget any leftovers.
    $lines[] = $line . $word;
    $start = 0;
    foreach($lines as $line) {
      $length = strlen($line);
      
      // We can get a new line by specifying where it starts within the
      // current paragraph ($start), how long it is ($length), whether we
      // want it returned with (true) or without (false) tags, and whether
      // out $start/$length calculations are based on function getResultText()
      // (true) or getResultNewText() (false).
      $new_text.= trim($handle->getLine($start, $length, $tags, $input)) . "<br />\r\n";
      $start+= $length;
    }

    // Each time we change paragraph, we need to inform PHPBiDi
    $handle->changeParagraph();
    $new_text.= "<br />\r\n";
  }

  // Most browsers automatically render RTL text appropriately.
  // So, the following text will not read fine in your browser. However,
  // the order of characters in $new_text is correct in terms of visual
  // representation.
  return $new_text;
}
function myLinesOrig(&$handle, $tags = false, $input = false) {

  // constant('UTF8PATTERN') helps count utf-8 encoded characters
  $pattern = constant('UTF8PATTERN');

  // You can get the number of paragraphs through getResultNum().
  for ($i = 0;$i < $handle->getResultNum();$i++) {

    // Let's say that this time we decide to break lines at 80
    // characters per line or less.
    // Function getResultNewText() returns the text as it has been
    // changed at the end of the first stage of processing, i.e.
    // in this case, without any \r\n.
    preg_match_all($pattern, $handle->getResultText(), $matches);
    $lines = array();
    $space = 0;
    $start = 0;
    $counter = 0;
    $line = '';
    $word = '';
    for ($j = 0;$j < count($matches[0]);$j++) {
      if ($matches[0][$j] == ' ') {
        $line.= $word;
        $word = '';
        $start = $j;
      }
      if ($counter > 79) {
        $lines[] = $line . ' ';
        $j = $start;
        $counter = 0;
        $line = '';
        $word = '';
      } else {
        $word.= $matches[0][$j];
      }
      if ($matches[0][$j] == '<') {
        $j++;
        while($j < count($matches[0]) and $matches[0][$j] != '>') {
          $word.= $matches[0][$j];
          $j++;
        }
        $word.= $matches[0][$j];
        $counter--;
      }
      $counter++;
    }

    // We shouldn't forget any leftovers.
    $lines[] = $line . $word;
    $start = 0;
    foreach($lines as $line) {
      $length = strlen($line);
      
      // We can get a new line by specifying where it starts within the
      // current paragraph ($start), how long it is ($length), whether we
      // want it returned with (true) or without (false) tags, and whether
      // out $start/$length calculations are based on function getResultText()
      // (true) or getResultNewText() (false).
      $new_text.= trim($handle->getLine($start, $length, $tags, $input)) . "<br />\r\n";
      $start+= $length;
    }

    // Each time we change paragraph, we need to inform PHPBiDi
    $handle->changeParagraph();
    $new_text.= "<br />\r\n";
  }

  // Most browsers automatically render RTL text appropriately.
  // So, the following text will not read fine in your browser. However,
  // the order of characters in $new_text is correct in terms of visual
  // representation.
  return $new_text;
}?>
  </body>
</html>
Return current item: PHPBiDi